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,338,764 | 3,338,931 | Why is vector<Data*>::iterator valid and vector<Data*>*::iterator not? | I have these three related class members:
vector<Frame*>* poolFrames;
vector<Frame*>*::iterator frameIterator;
vector<vector<Frame*>::iterator>* poolFrameIterators;
When I compile, gcc tells me
error: invalid use of ‘::’
error: expected ‘;’ before ‘frameIterator’
In reference to the middle line, where I define fra... | I see what you were trying to do. You've defined poolFrames as a pointer to a vector. Then you want to define frameIterator as an iterator for poolFrames. Since poolFrames is a pointer, you think you need a special pointer-to-vector iterator, but you're mistaken.
A vector iterator is a vector iterator is a vector itera... |
3,339,196 | 3,339,709 | Referencing a member of a member in template | I'm using boost::multi_index_container and I'm trying to refer to a member of a member in a template argument, but it's unclear how to do this:
struct Foo {
int unique_value;
};
struct Bar {
Foo foo;
double non_unique_value;
};
// I want to refer to some_value in a template argument:
multi_index_container... | Questions about this feature pop-up from time to time, since it is indeed a very logical thing to have. But unfortunately it is not part of the language.
See this thread as well Is Pointer-to- " inner struct" member forbidden?
|
3,339,200 | 3,339,227 | Get String Between 2 Strings | How can I get a string that is between two other declared strings, for example:
String 1 = "[STRING1]"
String 2 = "[STRING2]"
Source:
"832h0ufhu0sdf4[STRING1]I need this text here[STRING2]afyh0fhdfosdfndsf"
How can I get the "I need this text here"?
| Since this is homework, only clues:
Find index1 of occurrence of String1
Find index2 of occurrence of String2
Substring from index1+lengthOf(String1) (inclusive) to index2 (exclusive) is what you need
Copy this to a result buffer if necessary (don't forget to null-terminate)
|
3,339,286 | 3,339,792 | Creating a template predicate class requiring a pointer to method function, and ensuing compiler errors | I'm building a series of predicates that duplicate lots of code, and so are being changed into a single template function class based on the std::unary_function. The idea is that my class interface requires methods such as Element_t Element() and std::string Name() to be defined, so the predicate template arguments are... | I don't know of any easy way to do this using the bits provided with the STL. There is probably some clever boost way, using iterator adapters, or boost::lambda, but personally I wouldn't go that way.
Obviously C++0x lambdas will make all this easy.
Your problem is attempting to cast a function like this:
const std::s... |
3,339,302 | 3,339,317 | Set a virtual function declaration to zero? |
Possible Duplicate:
Why pure virtual function is initialized by 0?
In C++, what does it mean to set a function declaration to zero? I'm guessing it has to do with the function being virtual, and not actually defined in this class. Found in a header file of code that I'm reading:
virtual void SetValue(double val)=0... | It's a pure virtual function. It makes it so you MUST derive a class (and implement said function) in order to use it.
|
3,339,547 | 3,339,912 | How to create table (array) with extern values? | I would like to create a static (file scope) table of data pointer, data size and data version. The problem is that the data are in external files, but constants in the extern files.
Example:
file1.c
const unsigned char data1[] =
{
0x65, 0xF0, 0xA8, 0x5F, 0x5F,
0x5F, 0x5F, 0x31, 0x32, 0x2E,
0x31, ... | The problem is that the compiler doesn't know the value to place into the data_size and data_version members of the field. There are a couple of ways you can get around this without too much fuss.
Approach 1:
#include "data1.c"
#include "data2.c"
...
static struct Data_Info Data_Info_Table[] =
{
{ data1, sizeof(dat... |
3,339,708 | 3,339,740 | Calculate percentage of 64 int | I have the following code:
typedef __int64 BIG_INT;
typedef double CUT_TYPE;
#define CUT_IT(amount, percent) (amount * percent)
void main()
{
CUT_TYPE cut_percent = 1;
BIG_INT bintOriginal = 0x1FFFFFFFFFFFFFF;
BIG_INT bintAfter = CUT_IT(bintOriginal, cut_percent);
}
bintAfter's value after the calculati... | double has a 52 bit mantissa, you're losing precision when you try to load a 60+ bit value into it.
|
3,339,984 | 3,339,999 | Static Variable Pointer? | Is this illegal/dangerous?
int* static_nonew()
{
static int n = 5;
return &n;
}
The compiler doesn't seem to have a problem with it, but is the pointer location itself protected from being overwritten when someone else needs memory?
EDIT: A little bit more of an explanation of why I asked this question. Note: ... | This is valid code, and useful.
A lot of singleton-factories are built like this.
|
3,340,002 | 3,340,553 | Architecture problem: access-queue block | There's a resource manager class. It helps us to access devices. But, of course, it should look for not to give access to one device for 2 processes at the same time.
At first I thought I wouldn't have any access queue. I thought there would be method like anyFree_devicename() that would return access handle if there i... | Your access queue is creating what is known as a dead-lock. Multiple clients become perpetually blocked because they are trying to take ownership of the same set of resources but in a different order.
You can avoid it by assigning a unique value to all your resources. Have the clients submit a list of desired resourc... |
3,340,273 | 3,340,411 | Is Intptr sufficient when marshalling for wrapping a c++ interface (all abstract) which works by passing interface handles? | I am trying to wrap an unmanaged c++ interface composed of several abstract structs (with all pure virtual methods) and a small factory namespace which returns handles (shared_ptrs) to these structs.
It seems that, because of this, I might be able to get away with merely marshalling pointers through as System.IntPtr ty... | I recommend defining a C API to be consumed by the .NET layer. Use void * or const void * for the "handle" types to your structures, and define an extern "C" function for each of the methods (including factory methods and the destructor). You can't marshal a shared_ptr<T> argument directly, so you need to use the void ... |
3,340,306 | 3,340,654 | Unresolved external symbol using Direct2D | I am trying to download and build the 'WIC Image Viewer usign Direct2D' from here, but when I build my solution, I am slapped with 56 errors that look like:
Error 1 error LNK2019: unresolved external symbol __imp__CoUninitialize@0 referenced in function _wWinMain@16 WICViewerD2D.obj
Error 2 error LNK2019: u... | It could most likely mean that your directory settings in the Visual Studio project aren't correctly set.
For VS2008, go to Tools-->Options-->Projects and Solutions-->VC++ Directories and set the appropriate include file path and library file path.
Make sure you referenced the correct library files by stating their nam... |
3,340,336 | 3,340,401 | Ending "recv()" loop when all information is Read using Winsock | I am having an issue in my recv() loop for winsock. I am trying to terminate the loop when iResult==0, however, the loop only ends when the socket closes. It appears to be hanging at the very last recv() where iResult would equal 0. So any ideas on how to terminate the loop effectively? My ultimate goal (whether iResul... | By default, instead of returning 0, recv blocks if there's no data to receive :
If no incoming data is available at
the socket, the recv call blocks and
waits for data to arrive according to
the blocking rules defined for WSARecv
with the MSG_PARTIAL flag not set
unless the socket is nonblocking. In
this c... |
3,340,502 | 3,340,684 | C++ overloaded function pointer | I am not able to get this to work:
template<class Input, class Output, class Index>
size_t pack(void (*copy)(Input, Input, Output),
size_t N, Input input, Output output,
const Index &index);
size_t K = pack(&std::copy<const double*,double*>,
M, C.data().begin(), C_.data().begin(... | You could make a design change. One might be make the return type a separate template parameter:
template<class R, class Input, class Output, class Index>
size_t pack(R (*copy)(Input, Input, Output),
size_t N, Input input, Output output,
const Index &index);
The return type is deduced (and subs... |
3,340,843 | 3,340,875 | Why do C programmers use typedefs to rename basic types? | So I'm far from an expert on C, but something's been bugging me about code I've been reading for a long time: can someone explain to me why C(++) programmers use typedefs to rename simple types? I understand why you would use them for structs, but what exactly is the reason for declarations I see like
typedef unsigned ... | Renaming types without changing their exposed semantics/characteristics doesn't make much sense. In your example
typedef unsigned char uch;
typedef unsigned long ulg;
belong to that category. I don't see the point, aside from making a shorter name.
But these ones
typedef uch UBYTE;
typedef unsigned int u32;
typedef s... |
3,341,148 | 3,341,186 | c++ typing confusion with operators << and [] | I am trying to print a value of an array element as cout << array[0], (where the array is some glorified class using operator[]), but the C++ typing system seems incredibly confusing. The GCC error is this:
example.cpp:44:20: error: no match for ‘operator<<’ in ‘std::cout << a_0.fixedarr<T, N>::operator[] [with T = int... | You should declare both T fixedarrRef::val() and fixedarrRef<T> &v in operator << const.
T val() const { return ref[0]; }
and
template <typename T>
ostream & operator << (ostream &out, const fixedarrRef<T> &v)
|
3,341,167 | 3,594,062 | How to implement HMAC-SHA1 algorithm in Qt | I'm trying to implement HMAC-SHA1 algorithm in my C++/Qt application.
I have a method for Sha1 algorithm available, I just need to understand the HMAC part of it.
This pseudocode is from wikipedia:
1 function hmac (key, message)
2 if (length(key) > blocksize) then
3 // keys longer than blocksize are shor... | This post has a working implementation:
/**
* Hashes the given string using the HMAC-SHA1 algorithm.
*
* \param key The string to be hashed
* \param secret The string that contains secret word
* \return The hashed string
*/
static QString hmac_sha1(const QString &key, const QString &secret) {
// Length of the ... |
3,341,313 | 3,341,341 | library for matrices in c++ | I have a lot of elements in a matrix and when I access them manually it takes a pretty long time to eliminate all the bugs arising from wrong indexing... Is there a suitable library that can keep track of e.g the neighbors,the numbering, if an element is in the outer edge or not and so on.
e.g.
VA=
11 12 13 14
21 22 23... | There is this: http://osl.iu.edu/research/mtl/
or this: http://www.robertnz.net/nm_intro.htm
If you Google it a bit, there's quite a few matrix libraries out there for C++.
|
3,341,617 | 3,341,865 | How to detect user inactivity in Qt? | How can I detect user inactivity in a Qt QMainWindow? My idea so far is to have a QTimer that increments a counter, which, if a certain value is passed, locks the application. Any mouse or key interaction should set the timer back to 0. However I need to know how to properly handle input events which reset; I can re-im... | You could use a custom event filter to process all keyboard and mouse events received by your application before they are passed on to the child widgets.
class MyEventFilter : public QObject
{
Q_OBJECT
protected:
bool eventFilter(QObject *obj, QEvent *ev)
{
if(ev->type() == QEvent::KeyPress ||
ev->ty... |
3,341,673 | 3,341,737 | Do templates shorten the size of source or binary or both | I read that templates are complied into different entities so does that mean the binary size will be same as we have complied it using different functions?
| They should shorten the source size (if they are reused) but not the binary size (the template is compiled for each different instantiation).
This differs from Java generics, where there is a full type erasure (generics only serve as a compile time verification of types) or C#, where generics are compiled into specific... |
3,341,820 | 3,342,066 | Which compiler for default templates args in function | Is there a compiler which would complile function template definition with new C++ feature namely default templates arguments in function definition?
| According to this, GCC supports default template arguments for function templates since version 4.3.
Note: to enable C++0x support in GCC, add -std=c++0x to your g++ command line.
|
3,341,885 | 3,342,695 | static initialization of Template classes for singleton object | We have a singleton template class as defines below
template<class T> class Singleton{
T& reference(){
return objT;
}
private:
T objT;
};
And another user defined class which uses this singleton
class TestClass{
static Singleton<TestClass> instance;
static TestClass * ge... | Ignoring the fact, that in your example there is no need for Singleton template, consider this simplified example (I am using structs to avoid access issues):
template <class T>
struct Singleton
{
T object;
};
struct TestClass;
typedef Singleton<TestClass> TCS;
TCS test1; // not ok, no definition of T... |
3,341,912 | 3,341,939 | Specifying template argument | How can I specify what is required to be a valid template argument? What I mean is let's for example take something like this:
template<class T>
void f(const T& obj)
{
//do something with obj
}
but I would like T to be only integer type so I would accept char, int, short unsigned etc but nothing else. Is there (I'm s... | Have a look at concept checking (http://www.boost.org/doc/libs/1_43_0/libs/concept_check/concept_check.htm).
|
3,342,035 | 3,342,120 | How many vptr will a object of class(uses single/multiple inheritance) have? | How many vptrs are usually needed for a object whose clas( child ) has single inheritance with a base class which multiple inherits base1 and base2. What is the strategy for identifying how many vptrs a object has provided it has couple of single inheritance and multiple inheritance. Though standard doesn't specify abo... | Why do you care? The simple answer is enough, but I guess you want something more complete.
This is not part of the standard, so any implementation is free to do as they wish, but a general rule of thumb is that in an implementation that uses virtual table pointers, as a zeroth approximation, for the dynamic dispatch y... |
3,342,150 | 3,342,162 | Which type to use when iterating a std::vector (without iterators)? | Perhaps this question is trivial, but thinking a second time about it I wonder how to do the following really the right way:
std::vector<K> v = ...;
for(T i=0; i<v.size(); ++i) {
const K& t = v[i];
// use t *and i*
}
What type should T be? int, unsigned int, int32_t, size_t (which would be the type of v.size()) or... | The type of i should be the same as the return value of size(), which is std::vector<K>::size_type. However, in practice, size_t will do just fine. If you use a signed integer type, then your compiler will probably warn about a signed/unsigned mismatch in the less-than comparison.
Normally you would use an iterator for... |
3,342,159 | 3,342,310 | Give a name to a boost thread? | Is it possible to give a name to a boost::thread so that the debuggers tables and the crash logs can be more readable? How?
| You would need to access the underlying thread primitive and assign a name in a system dependent manner. Debugging and crash logs are inherently system dependent and boost::thread is more about non-system-dependency, i.e. about portability.
It seems ( http://www.boost.org/doc/libs/1_43_0/doc/html/thread.html ) that the... |
3,342,202 | 3,372,893 | Capture server-client communication with tcpdump | I wrote a simple server and client apps, where I can switch between TCP, DCCP and UDP protocols. The goal was to transfer a file from the one to the other and measure the traffic for each protocol, so I can compare them for different network setups (I know roughly what the result should be, but I need exact numbers/gra... | There are many things wrong in the code.
The file size / transfer size is hardcoded to 4294967295 bytes. So, if the file supplied isn't that many bytes, you'll have problems.
In the sender, you aren't checking if the file read is successful or not. So if the file is smaller than 4294967295 bytes, you won't know it a... |
3,342,216 | 3,378,195 | passing C++ classes instances to python with boost::python | I have a library which creates objects (instances of class A) and pass them to a python program which should be able to call their methods.
Basically I have C++ class instances and I want to use them from python. Occasionally that object should be passed back to C++ for some manipulations.
I created the following wrapp... | boost::python knows all about boost::shared_ptr, but you need to tell it that boost::shared_ptr<A> holds an instance of A, you do this by adding boost::shared_ptr<A> in the template argument list to class_, more information on this 'Held Type' is here in the boost documentation.
To prevent instances being created from ... |
3,342,276 | 3,342,291 | What's the scenario difference between hash_map and map in STL? | Is there any principle to choose one over another between hash_map and map in STL?
| hash_map is useful if you are only looking elements by their key. A possible use-case for a hash_map would be a dictionary. If the elements need to be in order map is the container for that.
And just for clarification (because of the usage of the word "STL"): hash_map isn't yet part of the C++ Standard Library, but it ... |
3,342,280 | 3,342,353 | Use stl vectors to manage opengl buffer objects | I don't think I am the first one to think about this ... but would it be possible to write a STL allocator that manages VRAM/Buffer Objects(BO) in OpenGL?
As a result of this Question I currently use vectors to write to and read from BOs.
Additionally i use some templating to map BOs as almost anything i like. Like th... | This article by Matt Austern is the classic reference for creating your own allocator. Allocator have their nooks and crannies, but when you know them writing your own isn't really all that hard.
|
3,342,283 | 3,342,383 | How to create static background image in OpenGL(GLUT) scene? | I create some scene, and i would like to display some static background image, which would not change from how and what I am doing with the scene.
| Usually it means that you can skip clearing your color buffer at the beginning of the scene, instead you set default orthographic projection and render a quad with (-1,-1,0), (-1,+1,0), (+1,+1,0), (+1,-1,0) vertices and apply a texture to this quad.
Then you can set necessary perspective projection and render whatever ... |
3,342,409 | 3,342,426 | Can I exhaust stack? | I know that by using operator new() I can exhaust memory and I know how to protect myself against such a case, but can I exhaust memory by creating objects on stack? And if yes, how can I check if object creation was succesful?
Thank you.
| You can exhaust a stack. In such cases, your program will probably crash with the stack overflow exception immediately.
A stack has a size too, so you can look at it as simply a block of memory. Variables inside functions for example are allocated here. Also when you call a function, the call itself is stored on the st... |
3,342,654 | 3,342,669 | cannot open output file debug\serbest.exe: Permission denied | I compile a Qt program with C++, and I got this error message:
cannot open output file debug\serbest.exe: Permission denied
collect2: ld returned 1 exit status
What are these command's meaning?
How do I get rid of these errors?
| Most likely cause: serbest.exe is still running. Check with TaskManager.
|
3,342,726 | 3,342,891 | C++: Print out enum value as text | If I have an enum like this:
enum Errors {
ErrorA = 0,
ErrorB,
ErrorC,
};
Then I want to print it out to console:
Errors anError = ErrorA;
std::cout << anError; // 0 will be printed
But what I want is the text "ErrorA". Can I do it without using if/switch? And what is your solution for this?
| Using map:
#include <iostream>
#include <map>
#include <string>
enum Errors {ErrorA=0, ErrorB, ErrorC};
std::ostream& operator<<(std::ostream& out, const Errors value){
static std::map<Errors, std::string> strings;
if (strings.size() == 0){
#define INSERT_ELEMENT(p) strings[p] = #p
INSERT_ELEMENT(Erro... |
3,342,801 | 3,342,950 | How to overload operator-> on a "generating" iterator? | I'm defining an iterator type that does not store its current value explicitly. Instead, it's a wrapper around another iterator, and returns std::pairs of the underlying iterator's values and another value. The relevant part of the class definition:
class MyIterator : public std::iterator<input_iterator, std::pair<Foo ... | I would suggest creating an own class holding the Foo* and Bar* pair, like this:
class MyPair {
private:
FooPtrIterator foo;
Bar bar;
public:
MyPair(const FooPtrIterator& it, const Bar& b) : foo(it), bar(b) {}
Foo* first() { return *foo; }
Bar* second() { return &bar; }
};
Then just use it inside your it... |
3,342,816 | 3,343,046 | Code in header files will always be inlined? | I just had a discussion with a coworker concerning code in header files:
He says that code defined in header files will always be inlined by the compiler (like the code from the function GetNumber() in my example header). I say it will be inlined sometimes, whenever the compiler decides to do so. So which one of us has... | Any function defined within the class (like your GetNumber example) rather than just declared is implicitly inline. What that means is that it's equivilent to using the inline keyword, so multiple inclusions of the header will not cause link errors due to multiple definitions of those functions.
Most modern compiler t... |
3,342,911 | 3,350,937 | Fast infoset or .net binary compression open source libraries | are there open source libraries implementing the fast infoset or the .net binary compression format?
I'd need them for C, C++ and C# (including support for the .net framework, I'm not sure it natively supports the binary compression).
The final goal is that of compressing xml files with a fast algorithm available for a... | The only open source Fast Infoset implementation is the one by Sun. This is the one being used by all Java vendors.
There are several C, C++ and C# implementations (incl for .NET/CF/SL) but they are all commercial. You might be able to get pricing/licensing terms that are suitable to your project if you contact the ven... |
3,342,931 | 3,343,097 | std::stringstream bugs? | I've got my own DLL which is being injected into another process. From the other process, the DLL sends IPC messages via boost::message_queue to my application. I'm using std::stringstream to construct the messages, as following:
class Client
{
...
private:
template <class T> void AddMessageParamete... | Your code fails when trying to send the longest message.
Therefore I assume that the message target is not reading fast enough.
I think your concept of trying 5 times is flawed, because you swallow your message if it didn't got sent - and you don't even handle this serious error case.
Personally I recommend to either ... |
3,342,943 | 3,348,879 | Strange crash with SQLite when finalizing a statement | I'm writing a C++ test app with SQLite, for which I made a small wrapper.
I'm repeatedly reading some data with it, and the fourth time I do, when finalizing the statement, it crashes. I'm sure I'm matching each prepared statement with a finalize. The 4th time, before the crash, the data has ben read successfully.
One... | I found the bug: it's how I manage the liftime of the SQLiteResultSet object!
SQLiteGateway is holding a ref of the last resultset produced, and if it's not null, deletes it before the next query. However I might have deleted it already somewhere else, which is actually what I'm doing! The resultset object no longer ex... |
3,343,251 | 3,343,350 | C++ statement analysis | I am seeing a code where in the program it is creating a hash_map:
// Create a hash_map hm3 with the
// allocator of hash_map hm1
hash_map <MyStr, MyInt>::allocator_type hm1_Alloc;
hm1_Alloc = hm1.get_allocator( );
hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > > hm3( hash_compare <MyStr, less_... | hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > >
This is a type, being a hash map which maps a MyStr to a MyInt, using a custom hash compare functor type. Let's call it HashMap.
hash_compare <MyStr, less_str > ()
The syntax T() creates a temporary object of type T using the default constructor. The code abov... |
3,343,553 | 3,344,398 | Using Wide Character Constants with clang Gets "extraneous characters in wide character constant ignored" Error | I recently decided to switch to clang from gcc and I’m getting the following warning for my use of wide character constants: "extraneous characters in wide character constant ignored". Here is the code that gets the warning:
wstring& line;
…
for (wstring::iterator ch = line.begin(); ch != line.end(); ++ch)
switch (... | At the heart of the program is the interpretation of the source file. You know that it's UTF-8 encoded. That's why the 6 bytes L'﹤' are to be interpreted as 4 Unicode characters. But how would clang know? It sees 6 bytes, and assumes an 8 bit encoding. Thus, it sees L'xyz' (the precise characters depend on the assumed ... |
3,343,610 | 3,343,666 | Extract a tar.xz in C/C++ | I am writing a program that downloads tar.xz files from a server and extracts them in a certain place. I am struggling to find a away of extracting the tar.xz file in the certain place. I am using Qt so a more Qt-way of doing it would be useful, but I don't really mind.
| There is no support for archives in Qt. You can either have a look at the KDE library which offers support for virtual file systems or you can use QProcess to call tar directly. Use -C <dir> (uppercase C) to specify the directory to extract to.
[EDIT] There also is libtar (BSD license).
|
3,343,779 | 3,344,040 | HALF_PTR Windows data type | The VS documentation states
Half the size of a pointer. Use within a structure that contains a pointer and two small fields.
Windows Data Types
What, exactly, is this type and how is it used, if ever?
|
Use within a structure that contains a pointer and two small fields.
This means that in the following structure, no padding is required:
struct Example {
void* pointer;
HALF_PTR one;
HALF_PTR two;
};
Of course, this is only relevant if the size of HALF_PTR (32 bits on a 64-bit system, 16 bits on a 32-bit... |
3,343,918 | 3,343,951 | Crash Analysis on Linux | What is the best way to analyze crashes on Linux?
We expect to build the software and deliver a release version to testers. The testers may not be able remember how to reproduce the crash or the crash may be totally intermittent. They also will not have a development environment on their machines. The software is writ... | I believe what you're looking for is this: How to generate a stacktrace when my gcc C++ app crashes
|
3,343,976 | 7,381,720 | Subsequent insertion of records with QSqlTableRecord fail after first error | I have a problem with inserting data into SQLite database using QSqlTableModel. The table is created like this:
QSqlQuery createTblSMS("CREATE TABLE sms_tbl("
"isRead BOOLEAN NOT NULL,"
"readTime DATETIME,"
"arrivalTime DATETIME NOT NULL,"
"sender TEXT NOT NULL,"
"receiver TEXT N... | I ran into this problem of two fold.
When you are in manual submit mode, QSqlTableModel does not clear its cache when a submitAll fails (which it should when you send it a record that violates your constraints).
To correct this, you need to call either call select() or revertAll to remove those pending changes.
The do... |
3,344,028 | 3,344,656 | How to make boost::thread_group execute a fixed number of parallel threads | This is the code to create a thread_group and execute all threads in parallel:
boost::thread_group group;
for (int i = 0; i < 15; ++i)
group.create_thread(aFunctionToExecute);
group.join_all();
This code will execute all threads at once. What I want to do is to execute them all but 4 maximum in parallel. When on i... | Another, more efficient solution would be to have each thread callback to the primary thread when they are finished, and the handler on the primary thread could launch a new thread each time. This prevents the repetitive calls to timed_join, as the primary thread won't do anything until the callback is triggered.
|
3,344,070 | 3,344,092 | C++ object termination notification | In a C++ program, I have two reference counted objects: King and Heir. Heir needs to block until King is destroyed. King is a reference counted object which will be destroyed when it's reference count goes to zero. If Heir holds a reference to King, then King's reference count will never go to zero. How can have He... | You can use a non-owning (or "weak") reference, similar to how weak_ptr works.
As for waiting until the king is dead, you can use a mutex that the king can hold until he dies and have the heir block waiting for the king to release it.
If you need to have multiple heirs waiting and there is some ordering to the heirs, y... |
3,344,173 | 3,346,889 | Automatically choosing object files for compilation | I have recently begun writing unit tests (using GoogleTest) for a C++ project. Building the main project is fairly simple: I use GCC's -MM and -MD flags to automatically generate dependencies for my object files, then I link all of the object files together for the output executable. No surpirses.
But as I'm writing ... | It sounds like you have two groups of source files: one that actually implements your program, and another that's all the unit tests. I assume each unit test has its own main function, and unit tests never need to call each other.
If all that's true, you can put all the files from the first group in a static library, ... |
3,344,242 | 3,347,058 | what could be reason for virtual bytes to grow 2x private bytes? | An application's virtual bytes grow 2-times the private bytes.
does this indicate memory leak? bad application design?
OS is 32Bit
any thoughts are welcome.
application is stream database.
| Fragmentation.
If you allocate the following chunks of memory:
16KB
8KB
16KB
and you then free the chunk of 8KB, your application will have 32 KB of private bytes, but 40 KB bytes of virtual memory, which is actually the highest virtual memory address that has ever been in use by your process (ignoring the other memo... |
3,344,395 | 3,344,410 | Force execution of parent's method before child's method without explicit call | I'm working on a c++ app and I'm facing a problem:
I have a class B derived from the abstract class A that has some event handling methods. A third class C is derived from B and must reimplement some of B methods. Is there a way to implicitly call B's method before calling C's one?
Class diagram:
class A
{
virtual ... | You have to explicitly call the base class method.
class C : public B
{
virtual void OnKeyPress(event e)
{
B::OnKeyPress(e);
// Do stuff
}
};
Just re-read your question.....
Best thing to do is to implement method in B that lastly calls an additional protected virtual method to be implement... |
3,344,583 | 3,344,777 | changing GLUT calls to work with MFC/C++ | I have a program that uses GLUT for its OpenGL rendering. Now I need it to be inside of a MFC project so that it can work with another program component.
I've followed this tutorial: http://www.codeguru.com/cpp/g-m/opengl/openfaq/article.php/c10975__1/Setting-Up-OpenGL-in-an-MFC-Control.htm
I am calling the function t... | I just browsed the tutorial you've linked to; on page two, something along the following lines can be found (I cleaned up the code a little bit):
void COpenGLControl::OnTimer(UINT nIDEvent)
{
if(nIDEvent==1)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
oglDrawScene();
// tr... |
3,344,690 | 3,345,367 | C++ on Windows: executable path with whitespace in system() call | I am trying to execute a file with parameters using the "system()" function in C++ on Windows, and it works as long as there are no whitespaces in the filename. For parameters, putting double quotes around the string works, but when I try the same with the executable itself, I get the following error:
"the filename,dir... | Use a string like this:
cmd /S /C "your entire command line string"
See: How do I deal with quote characters when using cmd.exe
|
3,344,833 | 3,348,055 | charset-aware tests like isalpha() etc. and iterators - is there such thing? | I get a character string and the encoding charset, like iso_8859-1, utf-8 etc. I need to scan the string tokenizing it to words, as I'd do using isspace() and ispunc().
Are there character test functions that take charset into account? Also, are there iterators that advance the correct number of bytes?
Note:
I know I c... | If you want to avoid the conversion at any cost, you would have to write a bunch of different routines:
static void handle_iso_8859_1(const char *);
static void handle_iso_8859_15(const char *);
static void handle_utf_8(const char *);
static void handle_string(const char *s, const char *encoding) {
if (strcmp(encod... |
3,344,839 | 3,344,866 | Fastest way to read Left-Most bit from unsigned int (C++)? | What is the fastest way to read the Left-Most bit from unsigned int ?
| i >> (sizeof(unsigned int) * CHAR_BIT - 1)
The sizeof, multiplication, and subtraction will be computed at compile-time by any reasonable compiler, so this should become a single right-shift instruction, which is about as fast as you will get.
|
3,344,973 | 3,345,007 | What is the right way to free a std::vector of pointers in C++? | I searched StackOverflow but couldn't find the answer to this question.
Suppose I have a std::vector<Day *> vector_day - that is - a vector of pointers to Day object. Now I push_back to vector_day many elements:
vector_day.push_back(new Day(12));
vector_day.push_back(new Day(99));
vector_day.push_back(new Day(71));
...... | The best way is not to put pointers into the vector in the first place if you don't absolutely need to.
But if you do really need to have a vector of pointers, then the way you are doing it is just fine (but .clear() the vector afterwords, if it won't be immediately destroyed, so that it's not full of dangling pointers... |
3,345,003 | 3,345,099 | What does container invalidation in C++ mean? | I learned today about the term invalidation in context of C++ containers. Can anyone explain what it means?
It seems like you're not allowed to modify elements of a container in some way when looping over the container. But what way exactly?
Please help me understand this topic.
Thanks, Boda Cydo.
| Containers don't become invalidated -- iterators referring to elements in containers become invalidated.
An iterator is a handle to a particular item within a container. The iterator is valid so long as that item remains inside the container, and the container does not internally rearrange itself. An iterator is invali... |
3,345,159 | 3,345,203 | in C++ , what's so special about "_MOVE_H"? | I have a C++ file like this
#ifndef _MOVE_H
#define _MOVE_H
class Move {
int x, y;
public:
Move(int initX = 0, int initY = 0) : x(initX), y(initY) {}
int getX() { return x; }
void setX(int newX) { x = newX; }
int getY() { return y; }
void setY(int newY) { y = newY; }
};
#endif
And to my amaze... | just run grep _MOVE_H in /usr/include/c++ on your machine
for me :
c++/4.5.0/bits/move.h:#ifndef _MOVE_H
As a rule of thumb, don't use things (really anything) prefixed by _ or __. It's reserved for internal usage.
Use SOMETHING_MOVE_H (usually name of the company, ...).
I guess it's a new header used to add the move... |
3,345,205 | 3,345,235 | the functionalities of two lines of code | When I was trying to learn from an existing program, I could not understand what the following two lines of code try to do?
for(i=0;0==(x&1);++i)x>>=1;
if(0==(x-=y)) return y<<i;
Any explanations would be appreciated.
| for(i=0;0==(x&1);++i)x>>=1
Finds the least significant bit set to 1 in an integer
if(0==(x-=y)) return y<<i;
Subtracts y from x, and if the result is 0, returns y shifted over (toward the more significant bits) by i bits.
|
3,345,363 | 3,345,421 | Kill some processes by .exe file name | How can I kill some active processes by searching for their .exe filenames in C# .NET or C++?
| Quick Answer:
foreach (var process in Process.GetProcessesByName("whatever"))
{
process.Kill();
}
(leave off .exe from process name)
|
3,345,611 | 3,345,941 | Data Structures... so how do I understand them? | So I am a Computer Science student and in about a week or so... I will be retaking a Data Structures course, using C++ for applying the theory. Yes, I did say "retaking". I took the course last Fall and I feel like there is more that I need to learn. Being a student, I feel that I MUST know the basics because it will b... | You have received some interesting links and ideas already. I hope I can provide a little different point of view:
I learned to visualize and "like" data structures by being taught that computer memory is like a really long list. The structures then have different layout in the memory. By visualizing the structures in ... |
3,345,994 | 3,346,026 | C++ , is this goto statement warranted? | I have changed title slightly because I thought this is more appropriate question.
Would you refactor it (seems like legitimate use of goto) ?
If, how would you refactor the following code to remove go to statement?
if (data.device) {
try {
...
}
catch(const std::exception&) { goto done; }
...... | if (data.device)
{
bool status = true;
try
{
...
}
catch(std::exception)
{
status = false;
}
if (status)
{
... // more things which should not be caught
}
}
|
3,346,051 | 3,346,075 | std::swap returns 0xBAADF00D | I'm trying to swap two std::list< dontcare* >::iterators under Visual 2005.
Iter it1 = ... ,it2 = ...; // it1 and it2 are ok, not end() or such
if(...){
std::swap(it1,it2);
}
The swap works, but when I leave the if() scope, it1 points to 0xbaadfood. It2 is ok though.I tried several variations, including swap_iter ... | Are you omitting code inside your if? Most likely something else within your if check, but after the swap is actually invalidating the iterator (perhaps an erase).
|
3,346,244 | 3,346,432 | PostMessage: Access Denied | The application shall receive messages from all processes of the system. Messages are sent using PostMessage call, which returns an error (5, access denied).
The code works correctly on Windows XP SP2, but on Windows 7 application receive messages from only itself, which it should be supposed to get message from every... | You can allow your program to receive a specific message by using ChangeWindowMessageFilterEx function.
|
3,346,441 | 3,346,543 | Solving the array sum problem using iterators and testing for equality only | While getting ready for interviews, I decided to code the classic "Find if there are two elements in an array that sum up to a given number" question using iterator logic, so that it can be generalized to other containers than vector.
Here's my function so far
// Search given container for two elements with given sum. ... | First of all, your algorithm is wrong unless you've somehow determined ahead of time that you only need to look at sums where one item is in the first half of the collection, and the other is in the second half of the collection.
If the input's not sorted, then @sbi's answer is about as good as it gets.
With a sorted, ... |
3,346,446 | 3,354,043 | C++ Singleton Threading problem | I have a C++ singleton that runs as a separate thread. This singleton is derived from a base class provided by a library and it overrides the method onLogon(...). The onLogon method is synchronous, it wants to know right away if we accept the logon attempt.
Problem is we need to pass the logon information via message... | I ended up going with boost::promise and boost::unique_future. It's was perfect for what I needed.
http://www.boost.org/doc/libs/1_43_0/doc/html/thread/synchronization.html#thread.synchronization.futures
|
3,346,690 | 3,346,806 | When Does Visual Studio 6 Catch Structured Exceptions? | This is mostly curiosity, but I've been reading about the history of Visual Studio catching SEH exceptions in a C++ try-catch construct. I keep running across the assertion that older versions Visual Studio with the /GX flag enabled would "somtimes" catch structured Win32 exceptions in a C++ catch block.
Under what ci... | int main()
{
__try
{
int *pInt = NULL;
*pInt = 0;// throw some kind of exception
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
DWORD dw = GetExceptionCode();
switch(dw)
{
case EXCEPTION_ACCESS_VIOLATION:
cout << "access violation\n";
... |
3,346,704 | 3,348,128 | Symbian C++ - synchronous Bluetooth discovery with timeout using RHostResolver | I am writing an application in Qt to be deployed on Symbian S60 platform. Unfortunately, it needs to have Bluetooth functionality - nothing really advanced, just simple RFCOMM client socket and device discovery. To be exact, the application is expected to work on two platforms - Windows PC and aforementioned S60.
Of co... | The code you have looks ok to me. You've missed the usual pitfall of not consuming all the requests that you've issued. Assuming that you also cancel the timer and do a User::WaitForRequest(timerStatus) inside you're error handing condition, it should work.
I'm guessing that what you're worrying about is that there's n... |
3,346,754 | 3,347,290 | Qt - Real time drawing | I want to show a car's path in a window in real time, how to do that, and what classes I have to use. Is there anything like drawing area, in Qt.
Any Help will be appreciated.
| You'll need to read up on QGraphicsview. There are several helpful examples that show every bit of what functionality is present here. The implementation itself... I guess it's just a bunch of QLines on a QGraphicsScene. The realtime part is handled by calling repaint or paintevent or whatever it's called periodically,... |
3,347,001 | 3,347,010 | 'do...while' vs. 'while' |
Possible Duplicates:
While vs. Do While
When should I use do-while instead of while loops?
I've been programming for a while now (2 years work + 4.5 years degree + 1 year pre-college), and I've never used a do-while loop short of being forced to in the Introduction to Programming course. I have a growing feeling th... | If you always want the loop to execute at least once. It's not common, but I do use it from time to time. One case where you might want to use it is trying to access a resource that could require a retry, e.g.
do
{
try to access resource...
put up message box with retry option
} while (user says retry);
|
3,347,031 | 3,347,060 | can i calculate normals in gpu? | I have an opengl application that loads a dxf and draws it on the screen,
each time i need to calculate normals. is there a way to calculate normals in GPU instead of CPU ? if so how ?
| Yes, it's possible. You will want to learn about Shaders in Cg.
Official book.
|
3,347,086 | 3,347,098 | Operator commutativity for inequality != in C++ | I have a quick question about the following expression:
int a_variable = 0;
if(0!=a_variable)
a_variable=1;
what is the difference between "(0 != a_variable)" and "(a_variable != 0)" ?
I dont have any errors for now but is this a wrong way to use it??
| if you forget the !, the first will give an error (0 = a_variable) and the second will wreak havoc (a_variable = 0).
Also, with user-defined operators the second form can be implemented with a member function while the first can only be a non-member (possibly friend) function. And it's possible, although a REALLY bad ... |
3,347,346 | 3,347,403 | C++ Conditional Operator | I once seen a -wired- operator in C++ which assigns value if greater than..
it was a combination of ?, < and =
e.g. let x = value if value is greater than x
I do not mean x=(x<value)x:value
It was some sort of x<?=value
But I can not remember it exactly, and can not find it online... Can some one remind me of it?
Thank... | gcc has -- in version 3.3.6 at least! -- a gcc-specific language extension providing specialized operators for implementing min and max. Perhaps this is what you are thinking of?
Minimum and Maximum Operators in C++
I don't have gcc handy to test it with, but it might have an updating form, too.
|
3,347,568 | 3,347,802 | How can I resolve this address of overloaded member function issue? | [EDIT - I long since forgot this was here until I got the 2,500 views "notable question". Since people are viewing - there is useful information about overloads in the accepted answer, but specifically checking for std::endl is even worse than I realized at the time, and definitely the wrong thing.
Basically, the effec... | The use of an overloaded function name, (or the name of a function template which behaves like a set of overloaded functions) without arguments (such as in an "address of" expression) is only allowed in a limited set of contexts where the context can be used to uniquely determine the particular overload required.
This ... |
3,347,774 | 3,359,500 | Dynamic linking a library - successful when executable is built, same setup fails when another .so is made | I am writing a numerical code, in which I would like to use a third-party-written shared library. I am working on an x86_64 k8 architecture, under CentOS. The desired target that I would like to build would be either a Python or a Matlab extension module, which are, from what I understand, gcc-built dynamically-linked ... | In general, glibc and libstdc++ try to provide backwards compatibility -- a binary built on an older system (or with older GCC) continues to run on a newer system.
The reverse: running binary linked against glibc-2.10 on a glibc-2.5 system, or running a binary built with GCC-4.4 against libstdc++ which came with GCC-4.... |
3,347,829 | 3,347,861 | How to execute C++ code without compiling it? | In order to pass some code to an application created with C++ I have used a C++ open source code which acted as a TCL interpreter. So I could create a file, in there put some XML data and in some tags some TCL code. Finally it is possible to read the file configure some structure and execute the TCL script snippets fro... | CINT
Archived CINT old official page from web.archive.org
Original inventor "Masaharu Goto" CINT page (CINT : C++ interpreter)
What is CINT?
CINT is an interpreter for C and C++ code. It is useful e.g. for situations where rapid development is more important than execution time. Using an interpreter the compile and ... |
3,347,831 | 3,356,157 | Getting current time of a different timezone using C++ | How do i get the current time of a different time zone? Example, i need to know the current time in Singapore where as my system is set to PT time.
| One implementation would be to use time to get the current time in UTC and then manipulate the TZ environment variable to your destination timezone. Then use localtime_r to convert to that timezone's local time.
|
3,347,835 | 3,348,893 | C++: Check if bmp file is legit | I'm using C++ (Visual Studio) and I want to check if a .bmp file is legit (not some renamed virus.exe) before the user can share it over the internet with other users using my application.
I'm using DirectX 2d rendering and boost framework.
Is there an (easy?) way to validate bitmaps?
Thanks.
| You can try loading the bitmap with Win32 LoadImage, which should fail for malformed bitmaps.
As others have mentioned, you can check the bitmap header and sanity check things like the file size (based on what you find in the header). That would be faster than LoadImage, but it's a lot of code to write and test. Ther... |
3,347,904 | 3,348,080 | dynamic memory allocation | here is example how Pointers are used to store and manage the addresses of dynamically allocated blocks of memory
#include <iostream>
#include <stdio.h>
using namespace std;
struct Item{
int id;
char* name;
float cost;
};
struct Item*make_item(const char *name){
struct Item *item;
... | At row 11
item=malloc(sizeof(struct Item));
must become
item=(Item *)malloc(sizeof(struct Item));
At row 20
item->name=malloc(strlen(name)+1);
must become
item->name=(char *)malloc(strlen(name)+1);
At row 21
if (item->name=NULL){
must become
if (item->name==NULL){.
|
3,348,120 | 3,348,139 | How do I get the size of a file after ftp'ing? | CFtpFileFind finder(mConnection);
found = finder.FindFile("*.log");
while (found)
{
found = finder.FindNextFile();
wsprintf(fileInfo, "%s", finder.GetFileName());
//need file size of this .log
//no member function for this in CFTPFileFind class?
}
EDIT Answer
finder.G... | CFtpFileFind seems to derive from CFileFind which has a GetLengh().
|
3,348,223 | 3,348,345 | In C++, in the definition of functions, the argument identifiers are optional. In which scenario this feature could be useful? | int foo(int){
...
}
Any ideas?
| One case where you define a function but do not name the parameter is given in Scott Meyers's "Effective C++, 3rd edition", Item 47:
template<typename IterT, typename DistT>
void doAdvance(IterT& iter, DistT d,
std::random_access_iterator_tag)
{
iter += d;
}
is used in:
template<t... |
3,348,419 | 3,348,530 | MSVC 2010 templates compiler problem | 1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\list(1194): error C2451: conditional expression of type 'void' is illegal
1> Expressions of type void cannot be converted to other types
1> C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\list(1188) : while compiling class... | It seems you have problems with instantiation. I've just tried to reproduce your bug but my MSVC compiled this code successfully.
Please, show us more code )) For example, show us how you use this list after creation.
|
3,348,535 | 3,348,565 | How to deal with failed constructor when throwing exceptions is not allowed | I was looking at the Google C++ Style Guide and they have decided not to use exceptions in C++ code, relying on return values instead.
My question is: How do you handle failure in constructors in this case, since you cannot return a value in those.
Thanks!
| My first instinct would be to take the failure point out of the constructor, and create an initialisation method.
This way you can create your object without fear of failure, then call the init() function. That function can return something like an int for success/failure, for example -1 if the failure occurs.
Yes thi... |
3,348,541 | 3,348,595 | writing unmanaged DLL consumable by C#/.NET code | I need to implement a small part of my application logic in native code.
To test PInvoke capabilities I created a simple solution with an unmanaged C++ Win32 Dll and a WPF project that consumes the dll functions using PInvoke.
The problem I run into is that i receive exception about "unbalancing the stack" and "possibl... | solved :) it seems i forgot __stdcall keyword in c++ function definition It should have been: __declspec(dllexport) int __stdcall add(int a, int b)
|
3,348,807 | 3,348,819 | Using popen to write in a pipe only send data when pipe is closed | I'm using popen to open a write pipe and send commands to an application. The problem is that the commands are only sent to the application when I close the pipe.
FILE * fp = open(target_app, "w");
fwrite(command, 1, command.size(), fp);
getchar(); //wait for a key, because I don't want to terminate the application
pcl... | I just figure it out that I have to flush the pipe to send commands without the need to close it. My fix was:
FILE * fp = open(target_app, "w");
fwrite(command, 1, command.size(), fp);
fflush(fp);
getchar(); //wait for a key, because I don't want to terminate the application
pclose(fp); // at this point, the command is... |
3,348,936 | 3,350,264 | array of arrays of different size | I've some code that produces a set of tr1::array of different sizes, but same type, like
array<int, 2>
array<int, 4>
array<int, 6>
The number of these arrays, and their sizes, are given in compile time, so I know exactly how many of them there will be and how's big each one (but they may be different).
Problem: I woul... | I would use Boost's MPL and Fusion libraries. There are two ways of ending up with the type list: generate them, or explicitly define them. The former is bit more flexible, but it's hard to say which is right for you since we don't know how you get the values you have.
In any case, generating:
#include <boost/mpl/for_e... |
3,349,027 | 3,349,641 | Unicode, char pointers and wcslen | I've been trying to use the cpw library for some graphics things. I got it set up, and I seem to be having a problem compiling.
Namely, in a string header it provides support for unicode via
#if defined(UNICODE) | defined(_UNICODE)
#define altstrlen wstrlen
#else
#define altstrlen strlen
Now, there's no such thing a... | Maybe you can define wcslen as wstrlen before including the lib header:
#define wstrlen wcslen
#include "cpw.h"
The error you are getting is likely to be due to you passing a char* that into something that ends up calling one of those functions.
|
3,349,459 | 3,349,650 | General formula to generate a cubic bezier elliptical arc? | How could I implement in C a simple way to generate the 2 missing control points for an elliptic arc given a start and end point? I don't need fancy error estimation, just something that can take points A and D and generate the control points B and C for the elliptical arc where I can then use the cubic bezier interpol... | There are some flaws in the math behind your question:
Bézier curves are polynomial functions of a parameter t in the unit interval [0;1]. Ellipses are defined using the trigonometrical functions, which are transcendental, thus, not algebraic, thus, not polynomial. You cannot generate an ellipse arc using Bézier curve... |
3,349,538 | 3,349,550 | C++ Set object member as reference/pointer of member of a different object? | (I'm not sure if that title is worded correctly, as I'm still new to C++)
I have two classes, loosely represented here:
class SuperGroup
{
public:
LayoutObj theLayout;
}
class SomeClass
{
public:
LayoutObj myLayout;
SuperGroup myGroup;
}
During SomeClass's constructor, I want to set myGroup.theLayout to b... | You do indeed need a pointer. Try using:
LayoutObj *theLayout;
Without a pointer, you are trying to assign a LayoutObj to a memory address. This may compile, but is not the behavior you want. Instead, you need a pointer to point to the memory address of a LayoutObj.
The line myGroup.theLayout = &myLayout; remains t... |
3,349,642 | 3,349,647 | Will std::multimap preserve the insert order if the key of 2 elements equal to each other? | I am wondering whether this is true? If it is, is this behavior guaranteed by the c++ standard?
| The elements in a std::map must have unique keys, so... no.
The std::multimap container allows multiple values mapped to one key. When iterating over a std::multimap the elements are ordered by key, but the order of elements having the same key is not specified.
Note that in the latest draft of the forthcoming C++0x s... |
3,349,655 | 3,349,714 | Are the elements in a std::map guaranteed to be ordered? | Is this just an implementation side effect (red-black tree) or the order is guaranteed by the c++ standard?
| Ordered iteration is not an implementation detail; it is guaranteed by the C++ standard. It is a fundamental property of all associative containers (C++03 §23.1.2/9):
The fundamental property of iterators of associative containers is that they iterate through the containers in the non-descending order of keys where n... |
3,349,789 | 3,349,901 | how to close specific serial port in C++ MFC smart device application? | how to close specific serial port in C++ MFC smart device application?
how to check if a port is open?
and how to close it?
i am using this "
ex: http://msdn.microsoft.com/en-us/library/ms881795.aspx
| To close handle that you have got from CreateFile you should use CloseHandle function.
|
3,349,956 | 3,351,027 | Portable C++ build system | I'm looking for a good and easy in maintenance portable build system for C++ projects. Main platforms should include Windows (Visual Studio 8+) and Linux (gcc); Cygwin may be an advantage. We're considering two main possibilities: CMake and Boost.Jam. SCons can be also an option, but I haven't investigated it yet. CMak... |
(-) demands a configuration file in every project folder
This is not correct, you just need to pass bigger pathes like:
add_program(foo src/foo.cpp src/main.cpp)
Few notes, about Boost.Jam - first it is not Boost.Jam - bjam on its own quite useless, what you are looking for is Boost.Build which is set of Jam macros ... |
3,350,048 | 3,350,078 | Circularly declaring Preprocessor directives? Or defines before includes? | I'm a bit new to C++, so bear with me. I'm trying to figure out where exactly to place my #defines and #includes in my project. I have something like this:
main.h
#include "other.h"
#define MAX_GROUPS 100
struct Cat
{
int something[MAX_GROUPS];
}
In other.h I also need to use MAX_GROUPS, so do I also define MAX_... | Minimising circular dependencies is very important in maintaining your project. For an extended discussion, see "Large Scale C++ Software Design" by John Lakos.
To avoid the specific problem you are having, define values in one header file, and include that header file in every file that needs it. To avoid problems wi... |
3,350,086 | 3,350,845 | ERROR_DEV_NOT_EXIST when ::CreateFile in C++ MFC? | I am writing to open a port using this function:
HANDLE hFile = ::CreateFile(pszComName, GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0,0);
// Check if we could open the device
if (hFile == INVALID_HANDLE_VALUE)
{
DWORD hh= ::GetLastError();
error.Format(_T("test - [%d]"),hh);
AfxMessag... | COM ports names in Windows CE/Mobile are in the format of COMX: - the difference is the colon - (for example COM1:).
Your code should look like this: CreateFile(L"COM1:",...)
You can also check the port name through the registry. If you have an ActiveSync connection, use a remote registry editor and go to [HKLM\Driver... |
3,350,375 | 3,350,745 | Call main thread callback function from worker thread | Scenario:
I have a c++ DLL.
In this DLL, I created a worker thread.
In the worker thread, I have a loop that waits for user input via a USB hardware device.
The loop ends only when the user input on USB device meets some criteria.
Additionally, I need to feedback the user usage feedback of the USB device real-time to d... | First off, I would not recommend using variables to communicate between threads. For your purpose, use an event.
Your DLL:
HANDLE _exitNow = NULL;
HANDLE _queueLock = NULL; // for part 2 below
// call this from your main at start
bool DLL_Initialize()
{
_exitNow = CreateEvent(...);
_queueLock = CreateMutex(... |
3,350,385 | 3,350,395 | How to "return an object" in C++? | I know the title sounds familiar as there are many similar questions, but I'm asking for a different aspect of the problem (I know the difference between having things on the stack and putting them on the heap).
In Java I can always return references to "local" objects
public Thing calculateThing() {
Thing thing = ... |
I don't want to return a copied value because it's inefficient
Prove it.
Look up RVO and NRVO, and in C++0x move-semantics. In most cases in C++03, an out parameter is just a good way to make your code ugly, and in C++0x you'd actually be hurting yourself by using an out parameter.
Just write clean code, return by va... |
3,350,480 | 3,350,529 | Datatype convertion problems | some days ago i've posted a question for a win32 API stacktrace implementation with MSYS/Mingw: Win32 API stack walk with MinGW/MSYS?
The hint with the explicit loading of the dll was the correct solution. So i've restart the try to implement a stacktrace using the win32 CaptureStackBackTrace API mechanism regarding th... | In the last stament, you need to invoke the function using function pointer func. So it should be num = func( 1, 32, array, NULL ); Otherwise, you are trying to create an unnamed object of type CaptureStackBackTraceType and trying it to convert to an int. Since the conversion doesn't exist, compiler is issuing an error... |
3,350,573 | 3,350,627 | A warning with cppcheck, "hides typedef with same name" | This is a cppcheck warning message.
Variable 'BUFFER_INFO' hides typedef with same name
The BUFFER_INFO is defined as following.
typedef struct tagBufferInfo
{
CRITICAL_SECTION cs;
Buffer* pBuffer1;
Buffer* pBuffer2;
Buffer* pLoggingBuffer;
Buffer* pSendingBuffer;
}BUFFER_INFO, *PBUFFER_INFO;
And... | This looks like it might be a cppcheck bug.
However... what you have written is bad C++ style, prefer:
struct BUFFER_INFO
{
CRITICAL_SECTION cs;
Buffer* pBuffer1;
Buffer* pBuffer2;
Buffer* pLoggingBuffer;
Buffer* pSendingBuffer;
};
I would also obsrve that it is not good C++ style to use all upperc... |
3,350,626 | 3,350,710 | What's the meaning of * and & when applied to variable names? | In C++, what is the difference between:
void func(MyType&); // declaration
//...
MyType * ptr;
func(*ptr); // compiler doesnt give error
func(ptr); // compiler gives error i thought & represents memory address so
// this statement should correct as ptr is only a pointer
// or address of... | The unary prefix operator &, when applied to an object, yields the address of the object: &obj.
The type modifier &, when applied to a variable about to be declared, will modify the variable's type to be a reference type: int&.
The same applies to *: When applied as a unary prefix operator to a pointer, it will derefe... |
3,350,760 | 3,350,805 | How to load a string from the resource of a different process? | I need to load a string which is placed in the resource dll of a different process, provided that the process will be running at the time of call.
I tried following code -
HMODULE hRes = ::LoadLibrary(_T("SomeResource.dll"));
TCHAR buffer[50];
::LoadString(hRes, IDS_SOME_ID, buffer, 50);
This code is work... | It might be a problem of finding "SomeResource.dll". When you run from the debugger, the executable is started from the project's path. If the DLL can be found from there. it's fine. When you run from outside the IDE, the executable is started from a different folder. It migh be that the DLL cannot be found from there.... |
3,350,852 | 3,350,957 | How to correctly fix "zero-sized array in struct/union" warning (C4200) without breaking the code? | I'm integrating some code into my library. It is a complex data structure well optimized for speed, so i'm trying not to modify it too much. The integration process goes well and actually is almost finished (it compiles). One thing is still bothering me. I'm getting the C4200 warning multiple times:
warning C4200: nons... | I'll assume that you do want this to be compiled in pure C++ mode, and that you don't want just to compile some files in C and some in C++ and later link.
The warning is telling you that the compiler generated copy constructor and assignment will most probably be wrong with your structure. Using zero-sized arrays at th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.