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 |
|---|---|---|---|---|
1,053,099 | 1,053,134 | How can i get content of web-page | i'm trying to get web-page data in string that than i could parse it. I didn't found any methods in qwebview, qurl and another. Could you help me? Linux, C++, Qt.
EDIT:
Thanks for help. Code is working, but some pages after downloading have broken charset.
I tried something like this to repair it:
QNetworkRequest *requ... | Have you looked at QNetworkAccessManager? Here's a rough and ready sample illustrating usage:
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass();
void fetch();
public slots:
void replyFinished(QNetworkReply*);
private:
QNetworkAccessManager* m_manager;
};
MyClass::MyClass()
{
m_manage... |
1,053,231 | 1,053,311 | Sprites in directx10 and texture filtering | Is it possible to set different texture filtering when working with sprites?
| Can you be more specific about how you're drawing the sprites?
Texture filtering is determined by the ID3D10SamplerState objects bound to the device. If you're using the ID3DX10Sprite interface, it won't change the shaders or the samplers for each set of sprites, only the textures. So whatever shaders and samplers you'... |
1,053,242 | 1,054,538 | Array of pairs of 3 bit elements | Because of memory constrains, I have to store some pairs of values in an array with 6 bits/pair (3 bits/value). The problem comes when I want to access this array as a normal one, based on the index of the pair.
The array looks like this
|--byte 0 | --byte 1 | --byte 2
|00000011 | 11112222 | 22333333 ... and so on... | How about this? It eliminates memory accesses for the masks and shift values. (Of course, the (non-portable) assumption is that char is 8 bit and short is 16 bit. It is also assumed that index * 6 does not overflow int.)
void GetPair(char *array, int index, int &value1, int &value2)
{
unsigned shift = 10 - index ... |
1,053,244 | 1,058,231 | Qt QSystemTrayIcon not sending activated signal | I'm trying to copy the Qt systray example here:
http://doc.qt.io/archives/4.6/desktop-systray.html
Things seem to be working except that the QSystemTrayIcon object is not sending an activate signal.
Here's my mainwindow.cpp code:
#include <QtGui>
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWind... | Well if anyone's interested, I found the issue. The problem was actually in the header file.
Here's the one that works:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
#include <QSystemTrayIcon>
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow();
private slots:
void iconActi... |
1,053,456 | 1,053,462 | Taking type of a template class | Is there a way for taking type of a template class, for example
//i have template function
template<typename T>
IData* createData();
//a template class instance
std::vector<int> a;
//using type of this instance in another template
//part in quotation mark is imaginary of course :D
IData* newData = createData<"typeOf... | Yes - Use boost::typeof
IData* newData = createData<typeof(a)>();
The new standard (C++0x) will provide a builtin way for this.
Note that you could give createData a dummy-argument which the compiler could use to infer the type.
template<typename T>
IData* createData(const T& dummy);
IData* newData = createData(a);
|
1,053,678 | 1,053,766 | Implementing a generic fixed size array with iterator support | I need an array where size is known at compile time. I know I can use std::vector or boost::array. But that's doesn't teach me how it works internally. Also I couldn't find how to add items into boost::array other than using the initializer. I have written the following code for a generic array. My intention is to get ... | 1 - How can I create my array like boost::array does? Something like
Array<int> ints = { 10, 12 };
In c++, you can only (currently) use a braces enclosed initializer list if your struct, union or c-style array meets the criteria of being an aggregate. To do such, according to the standard:
8.5.1.1 An aggregate is an a... |
1,053,986 | 1,054,825 | can a GC be implemented with C++ raw pointers? | I was wondering how a Garbage Collector can be implemented with C++ full power of pointers arithmetic. Also, In languages like Java, I can not assign literal addresses to references. In C++ it is very flexible.
I believe that C# has both, but again, the unsafe pointer in C# is the responsibility of the programmer.
EITD... | Pointer arithmetic isn't the fundamental problem. GC's have to deal with pointers being reassigned all the time, and pointer arithmetic is just another example of that. (Of course, if pointer arithmetic between pointers pointing to different buffers was allowed, it would cause problems, but it isn't. The only arithmeti... |
1,054,009 | 1,054,060 | How can I pass MemoryStream data to unmanaged C++ DLL using P/Invoke | I need your help with the following scenario:
I am reading some data from hardware into a MemoryStream (C#) and I need to pass this data in memory to a dll implemented in unmanaged C++ (using pointer ??).
The data read (into stream) is very large (megabytes). I understand that I can P/Invoke this dll but what I am not ... | If it's just expecting bytes you can read the MemoryStream into a byte array and then pass a pointer to that to the method.
You have to declare the external method:
[DllImport("mylibrary.dll", CharSet = CharSet.Auto)]
public static extern bool doSomething(IntPtr rawData, int dataLength);
Then, read the bytes from the ... |
1,054,171 | 1,054,198 | What does it take to become a Java expert? | I was just reading this thread and wondered if it's easier to become a Java expert than a C++ one? Is it because it's very easy to write wrong code in C++ while in Java you have less flexibility (memory management for example) which prevents you from writing code horrors? Or is it because C++ is just inherently harder ... | What does it take? Like anything, years of practice and countless mistakes.
And even then, your expertise will be in a handful of areas where you solved particular problem domains again and again; i.e., islands of expertise. Middleware and/or frameworks? Threading & concurrency? Maybe Swing/GUI Java applications? ... |
1,054,447 | 1,054,451 | Printing a char* in C++ | I'm writing a simple program. There is only one class in it. There is a private member 'char * number' and two function (there will be more, but first these should work correctly :) ).
The first one should copy the 'source' into 'number' variable (and I suppose somewhere here is the problem):
LongNumber::LongNumber(con... | In the LongNumber constructor you declare a new local variable named number and initialize it with a new char array:
char* number = new char[digits+1];
Instead you should leave out the char*, so that it doesn't look like a new variable declaration and uses the object member variable:
number = new char[digits+1];
With... |
1,054,496 | 1,054,501 | How to signify to the compiler that a function always throws? | When calling functions that always throw from a function returning a value, the compiler often warns that not all control paths return a value. Legitimately so.
void AlwaysThrows() { throw "something"; }
bool foo()
{
if (cond)
AlwaysThrows();
else
return true; // Warning C4715 here
}
Is there ... | With Visual C++, you can use __declspec(noreturn).
|
1,054,530 | 1,054,691 | Use file-only APIs in memory | Some APIs only support output to files. e.g. a library that converts a BMP to PNG and only has a Save(file) option - no in memory function. Disk IO is slow, though, and sometimes you just want in-memory operations.
Is there a generic solution to such a problem? Maybe a fake in-memory file of sorts that would allow one ... | Use named pipes.
Similar constructs exist for both Windowsand Unix (and this).
But I don't believe it worth the effort setting up all those constructs. Choose an alternative library or just write to disk if you may.
|
1,054,697 | 1,056,738 | Why isn't my new operator called | I wanted to see that a dynamically loaded library (loaded with dlopen etc.) really uses its own new an delete operators and not these ones defined in the calling program. So I wrote the following library.cpp
#include <exception>
#include <new>
#include <cstdlib>
#include <cstdio>
#include "base.hpp"
void* operator new(... | The problem is that on most UNIX platforms (unlike on Win32 and AIX) all symbol references by default bind to the first definition of the symbol visible to the runtime loader.
If you define 'operator new' in the main a.out, everything will bind to that definition (as Neil Butterworth's example shows), because a.out is ... |
1,055,195 | 1,055,201 | Does a FileStream object (.NETCF, C#) created using handle returned from Win32 API CreateFile (C++, P/Invoke) prone to .NET Garbage Collection | UPDATED QUESTION
Since the ctor is not supported by .NETCF (public FileStream(IntPtr handle, FileAccess access). Could you please suggest other ways of sharing large file in memory between managed and unmanaged code on a limited resource (RAM) platform. Basically I want to map the file in the upper region of 2GB user s... | Overall there is nothing wrong with this approach of using a native Create file and wrapping it in a FileStream object. This is a supported feature of FileStream.
n terms of garbage collection though there are really 2 things at play here.
The memory associated with the FileStream object. Yes this will be garbage ... |
1,055,208 | 1,055,217 | C++ data structure with lookuptime O(1), like java's hashmap in stl? | Is there such a structure in c++ standard library? I don't have access to anything else so unordered_map in tr1 cant be used (and boost etc).
What I have is a large number of custom class elements 100000+ which I need to store, and access them very fast O(1) on everage. I can't use arrays/vectors as the elements will b... | The problem is that the O(1) lookup is not standard. I am unsure about what boost has, but some STL implementations (like sgi) have hash_map. That's what you need.
Here is the documentation.
Just try out:
#include <hash_map>
Keep in mind if this works, it is not portable... but maybe for now that's ok, and later you c... |
1,055,299 | 1,055,309 | Is there any way to get some information at least for catch(...)? | Is there any way to get at least some information inside of here?
...
catch(...)
{
std::cerr << "Unhandled exception" << std::endl;
}
I have this as a last resort around all my code. Would it be better to let it crash, because then I at least could get a crash report?
| No, there isn't any way. Try making all your exception classes derive from one single class, like std::exception, and then catch that one.
You could rethrow in a nested try, though, in an attempt to figure out the type. But then you could aswell use a previous catch clause (and ... only as fall-back).
|
1,055,340 | 1,055,363 | C++ Meta Templates: A Good or Bad Design Choice? | I'm curious to find out if and when C++ meta templates are a good design choice for systems small to large. I understand that they increase your build time in order to speed up your execution time. However, I've heard that the meta template code is inherently hard to understand by many developers, which could be a prob... | Metaprogramming is just another tool in a (C++) programmers' toolbox - it has many great applications, but like anything can be mis- or over- used. I think it's got a bad reputation in terms of 'hard to use', and I think this mainly comes from the fact that it's a significant addition to the language and so takes a wh... |
1,055,387 | 1,055,407 | Throw keyword in function's signature | What is the technical reason why it is considered bad practice to use the C++ throw keyword in a function signature?
bool some_func() throw(myExc)
{
...
if (problem_occurred)
{
throw myExc("problem occurred");
}
...
}
| No, it is not considered good practice. On the contrary, it is generally considered a bad idea.
http://www.gotw.ca/publications/mill22.htm goes into a lot more detail about why, but the problem is partly that the compiler is unable to enforce this, so it has to be checked at runtime, which is usually undesirable. And i... |
1,055,398 | 1,055,445 | Differences between Conditional variables, Mutexes and Locks | For example the c++0x interfaces
I am having a hard time figuring out when to use which of these things (cv, mutex and lock).
Can anyone please explain or point to a resource?
Thanks in advance.
| On the page you refer to, "mutex" is the actual low-level synchronizing primitive. You can take a mutex and then release it, and only one thread can take it at any single time (hence it is a synchronizing primitive). A recursive mutex is one which can be taken by the same thread multiple times, and then it needs to be ... |
1,055,413 | 1,055,668 | Sending a Java UUID to C++ as bytes and back over TCP | I'm trying to send a Java UUID to C++, where it will be used as a GUID, then send it back and see it as a UUID, and I'm hoping to send it across as just 16 bytes.
Any suggestions on an easy way to do this?
I've got a complicated way of doing it, sending from Java to C++, where I ask the UUID for its least and most sign... | I got something working.
Instead of sending it across as two longs, I send it across as bytes, here is the Java code:
public static UUID fromBytes( ByteString byteString)
{
byte[] bytesOriginal = byteString.toByteArray();
byte[] bytes = new byte[16];
// Reverse the first 4 bytes
bytes[0] = bytesOrigi... |
1,055,452 | 1,055,563 | C++ Get name of type in template | I'm writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, which are for the most part not written by programmers, and so need a nice message about why the app failed to load e.g. something like:
Error parsing ... | Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:
template<typename T>
struct TypeParseTraits;
#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
{ static const char* name; }... |
1,055,471 | 1,132,960 | Numerical regression testing | I'm working on a scientific computing code (written in C++), and in addition to performing unit tests for the smaller components, I'd like to do regression testing on some of the numerical output by comparing to a "known-good" answer from previous revisions. There are a few features I'd like:
Allow comparing numbers t... | I ended up writing a Python script to do more or less what I wanted.
#!/usr/bin/env python
import sys
import re
from optparse import OptionParser
from math import fabs
splitPattern = re.compile(r',|\s+|;')
class FailObject(object):
def __init__(self, options):
self.options = options
self.failure ... |
1,055,576 | 1,055,889 | Non-member non-friend functions vs private functions | Herb Sutter has said that the most object oriented way to write methods in C++ is using non-member non-friend functions. Should that mean that I should take private methods and turn them into non-member non-friend functions? Any member variables that these methods may need can be passed in as parameters.
Example (befor... | I believe in free functions and agree with Sutter, but my understanding is in the opposite direction. It is not that you should have your public methods depend on free functions instead of private methods, but rather that you can build a richer interface outside of the class with free functions by using the provided pu... |
1,055,627 | 1,055,634 | Strange stdout behavior in C++ | I want my program to display the unix windmill while processing. There's a for loop and in every iteration theres a printf function:
printf("Fetching articles (%c)\r",q);
q is one of the characters in the windmill (-\|/) depending on the iteration number.
The problem is - it seems like in 100 iterations there are only... | Flush the output after writing each line:
printf("Fetching articles (%c)\r",q);
fflush(stdout);
Without doing this, normally stdout is buffered and only dumps its output when a newline is seen, or its internal buffer fills up.
|
1,055,643 | 1,080,822 | Crash with boost::thread | I am using wxwidgets together with boost::thread. The Thread is a worker thread which sends some Events to the GUI:
Thread creation:
thrd = boost::thread(boost::bind(workerFunction,this));
Send Message to the GUI:
wxPostEvent(loWindow, event);
wxSafeYield();
Under Windows I don't see any problems, but when starting t... | The problem was with the data I sent - for complex data you need to use custom events. I now implemented a custom event and it works.
For more information please see http://forums.wxwidgets.org/viewtopic.php?t=24663
Thank you for your help!
/mspoerr
EDIT: Updated the link. The old one was broken
|
1,055,661 | 1,055,686 | Bigint (bigbit) library | I'm looking for a c++ class/library that provides 1024 bit and bigger integers and bit operations like:
- bit shifting,
- bitwise OR/AND,
- position first zero bit
speed is crucial, so it would have to be implemented with some SIMD assembly.
| There are several, including GMP, but for speed, the best is likely TTmath. TTmath's design decision to use templated fixed lengths at compiletime lets it be quite fast.
|
1,055,744 | 1,056,028 | Using WTL with Codeblocks | I want to try WTL, but problem is i can't use Visual Studio for this. So i've codeblocks on my side. Is there any way i can use WTL with codeblocks ? I mean configuration/settings that i need to do for this ?
is it possible to use WTL with codeblocks?
Just to clear first, i tried google for this. No satisfactory suc... | I don't think it is possible unless you use codeblocks with the MS compiler AND get the version of Windows SDK that contains ATL (new ones don't, AFAIK). WTL is built on top of ATL.
|
1,055,756 | 1,055,762 | C++ dynamic memory detail | I'm a C and Java programmer, so memory allocation and OOP aren't anything new to me. But, I'm not sure about how exactly to avoid memory leaks with C++ implementation of objects. Namely:
string s1("0123456789");
string s2 = s1.substr(0,3);
s2 now has a new string object, so it must be freed via:
delete &s2;
Right?
M... | No,
Both s1 and s2 will get destructed when out of scope.
s1.substr() will create a temporary object that you don't have to think of.
|
1,056,244 | 1,060,324 | std::map and performance, intersecting sets | I'm intersecting some sets of numbers, and doing this by storing a count of each time I see a number in a map.
I'm finding the performance be very slow.
Details:
- One of the sets has 150,000 numbers in it
- The intersection of that set and another set takes about 300ms the first time, and about 5000ms the second tim... | I figured something out: if I attach the debugger to either RELEASE or DEBUG builds (e.g. hit F5 in the IDE), then I get horrible times.
|
1,056,254 | 1,057,722 | How to maintain a weak pointer to a parent in C++? | Is there a standard way of maintaining a weak pointer to a parent (which is created using a shared pointer) in a child object in C++?
Essentially, I need to implement something on the lines of the following:
Class B;
Class A
{
...
private:
B m_b;
};
Class B
{
....
public:
void SetParentPtr(const boost::shared_ptr<A... | There is an implicit conversion to weak_ptr, so you can use
void SetParentPtr(boost::weak_ptr<A> a) { }
directly.
check also boost::shared_from_this so the parent can give a pointer to himself without storing a weak_ptr explicitly.
Otherwise, this seems like a normal way to have a back-pointer. Just check whether the... |
1,056,364 | 1,056,370 | How to generate a OS independent path in c++ | I have a destination path and a file name as strings and I want to concatenate them with c++.
Is there a way to do this and let the program/compiler choose between / and \ for windows or unix systems?
| If you wanted to do it at compile time you could certainly do something like
#ifdef WIN32
#define OS_SEP '\\'
#else
#define OS_SEP '/'
#endif
Or you could just use '/' and things will work just fine on windows (except for older programs that parse the string and only work with '\'). It only looks funny if displayed t... |
1,056,411 | 1,056,442 | How to pass variable number of arguments to printf/sprintf | I have a class that holds an "error" function that will format some text. I want to accept a variable number of arguments and then format them using printf.
Example:
class MyClass
{
public:
void Error(const char* format, ...);
};
The Error method should take in the parameters, call printf/sprintf to format it and... | void Error(const char* format, ...)
{
va_list argptr;
va_start(argptr, format);
vfprintf(stderr, format, argptr);
va_end(argptr);
}
If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf instead of vsprintf. vsnprintf will prevent an acc... |
1,056,691 | 1,056,712 | How to start modification with big projects |
I have to do enhancements to an existing C++ project with above 100k lines of code.
My question is How and where to start with such projects ?
The problem increases further if the code is not well documented.
Are there any automated tools for studying code flow with large projects?
Thanx,
| There's a book for you: Working Effectively with Legacy Code
It's not about tools, but about various approaches, processes and techniques you can use to better understand and make changes to the code. It is even written from a mostly C++ perspective.
|
1,056,879 | 1,056,891 | How to represent 18bit color depth to 16bit color depth? | I'm porting a software that build from 16bit color depth to 18bit color depth. How can I convert the 16-bit colors to 18-bit colors? Thanks.
| Without knowing the device, I can only speculate. Devices are typically Red, Green, Blue so each color would get 6 bits of variation. That means 64 variations of each color and a total of 262,144 colors.
Any bitmap can be scaled to this display. If you take each component (say, red), normalize it, then multiply by... |
1,056,911 | 1,058,917 | C++ classes as instance variables of an Objective-C class | I need to mix Objective-C and C++. I would like to hide all the C++ stuff inside one class and keep all the others plain Objective-C. The problem is that I want to have some C++ classes as instance variables. This means they have to be mentioned in the header file, which gets included by other classes and C++ starts sp... | This sounds like a classic use for an interface/@protocol. Define an objective-c protocol for the API and then provide an implementation of that protocol using your Objective-C++ class. This way clients need only know about the protocol and not the header of the implementation. So given the original implementation
@int... |
1,056,921 | 1,057,046 | How to represent from 16bit color depth to 18bit color depth? |
Possible Duplicate:
How to represent 18bit color depth to 16bit color depth?
I'm porting a software that build from 16-bit color depth device to 18-bit color depth device? How can I represent the 18-bit color depth? Thanks.
| NOTE: This is just an edit of my answer to your previous question, since the two are so similar - you just have to reverse the process.
You will first of all have to access each of the colour components (i.e. extract the R value, the G value, and the B value). The way to do this will depend totally on the way that th... |
1,056,964 | 1,056,998 | Crash on assigning NULL to a pointer in C++(Qtopia-Core-4.3.3) on Linux | When,i try to assign null value to my pointer,it sometimes crashes on that line. The code is
something like this :
if(s_counter != NULL)
{
delete s_counter;
s_counter = NULL; // it sometimes crashes here.
}
This is not reproducable,100%,but it occurs frequently. Can anybody help in this?
| Note that although it is OK to delete a NULL pointer, it is not necessarily OK to delete a a non-NULL pointer. The pointer must have been allocated with new and must not already have been deleted. Note also that allocating NULL to deleted pointers can add to a false sense of security - simply checking for NULL is not e... |
1,057,158 | 1,057,173 | A question about printf arguments. C/C++ | We have the following code fragment:
char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'};
printf("%s\n", tab);
And I don't understand why we don't get an error / warning in the call to printf. I DO get a warning but not an error, and the program runs fine. It prints '12'.
printf is expecting an argument of type char *, ... | Example Source
#include <stdio.h>
int main( void ) {
char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'};
printf("%s\n", tab);
return 0;
}
Compile Warning
$ gcc test.c
test.c: In function ‘main’:
test.c:5: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[3]’
Pointers are Pointers
Th... |
1,057,221 | 1,057,245 | What are practical uses of a protected constructor? | Why would anyone declare a constructor protected? I know that constructors are declared private for the purpose of not allowing their creation on stack.
| When a class is (intended as) an abstract class, a protected constructor is exactly right. In that situation you don't want objects to be instantiated from the class but only use it to inherit from.
There are other uses cases, like when a certain set of construction parameters should be limited to derived classes.
|
1,057,425 | 1,057,451 | Excessive use of `this` in C++ | I'm dealing with a large code base that uses the following construct throughout
class MyClass
{
public:
void f(int x);
private:
int x;
};
void MyClass::f(int x)
{
'
'
this->x = x;
'
'
}
Personally, I'd always used and hence prefer the form
class MyClass
{
public:
void f(int x);
private:
int _x;
};
void M... | Your version is a bit cleaner, but while you're at it, I would:
Avoid leading underscore: _x is ok until somebody chooses _MyField which is a reserved name. An initial underscore followed by a capital letter is not allowed as a variable name. See: What are the rules about using an underscore in a C++ identifier?
Make... |
1,057,637 | 1,057,673 | C++ distributed programming | Is there any library for distributed in-memory cache, distributed tasks, publish/subscribe messaging? I have used Hazelcast in Java, I would like something similar.
I know that Memcached is an in-memory cache and even distributed, but it is missing the messaging and remote task.
I just need something to coordinate a cl... | MPI might be what you want:
http://en.wikipedia.org/wiki/Message_Passing_Interface
There are C++ hooks available in boost:
http://www.boost.org/doc/libs/1_39_0/doc/html/mpi.html
Here is an informative podcast about Open-MPI, which is an implementation of MPI:
http://twit.tv/floss50
|
1,057,724 | 1,057,788 | What happens if you increment an iterator that is equal to the end iterator of an STL container | What if I increment an iterator by 2 when it points onto the last element of a vector? In this question asking how to adjust the iterator to an STL container by 2 elements two different approaches are offered:
either use a form of arithmetic operator - +=2 or ++ twice
or use std::advance()
I've tested both of them wi... | Following is the quote from Nicolai Josuttis book:
Note that advance() does not check
whether it crosses the end() of a
sequence (it can't check because
iterators in general do not know the
containers on which they operate).
Thus, calling this function might
result in undefined behavior because
calling o... |
1,058,051 | 1,058,358 | Boost serialization performance: text vs. binary format | Should I prefer binary serialization over ascii / text serialization if performance is an issue?
Has anybody tested it on a large amount of data?
| I used boost.serialization to store matrices and vectors representing lookup tables and
some meta data (strings) with an in memory size of about 200MByte. IIRC for loading from
disk into memory it took 3 minutes for the text archive vs. 4 seconds using the binary archive
on WinXP.
|
1,058,117 | 1,060,191 | Extending Visual Studio 2003 C++ debugger using autoexp.dat and DLL | I know a solution would be to use VS 2005 or 2008, but that's not an option at the moment. I am supposed to write an extension to the VS 2003 C++ debugger to improve the way it displays data in the watch window. The main reason I am using a DLL rather than just the basic autoexp.dat functionality is that I want to be a... | This article might help you:
http://msdn.microsoft.com/en-us/library/aa730838(VS.80).aspx
|
1,058,295 | 1,058,368 | Learning more about distributed computing | I'm interested in learning more about distributed computing and how to do it - mostly in C++ but I'd be interested in C# as well.
Can someone please recommend some resources? I know very little to nothing about the topic so where should I start?
Thanks.
| Distributed computing encompasses quite a lot of areas. Is there a specific class of problem you are looking to solve?
If you are just starting off you might want to do some background reading before getting into language specifics. You could start from Wikipedia. The paper on the Fallacies of Distributed Computing is... |
1,058,444 | 1,058,465 | How to Connect SVN server in C++? | I want to connect an svn server and download one file to my computer by using C++. How can I make this?
| You have a few options:
Set up WebDAV and use HTTP.
Use the SVN client library and integrate using it.
I've done both approaches in the past. The SVN client library is actually quite easy to use.
Edit
The subversion client library is described in Version Control with Subversion. Pay particular attention to Chapter 3 ... |
1,058,897 | 1,058,921 | Can C++/CLI be used to call .NET code from native C++ applications? | I've done the other way around (calling pure C++ code from .NET) with C++/CLI, and it worked (for the most part).
How is the native-to-C++/CLI direction done?
I really don't want to use COM interop...
| You can always host the CLR in your native app.
|
1,059,024 | 1,059,139 | Is there a pattern which names managing evil static_casts | The following code is a simplified version of what I use for event dispatching. The essential point is
that there is a static_cast<T*> on the argument of a template functor and another class makes
sure that the argument passed to the functor is what the static_cast casts to.
struct AbstractArg {
virtual ~AbstractAr... | This isn't an anti-pattern, it's a really useful technique often used with type erasure.
|
1,059,062 | 1,059,076 | In C++, how to get the address in which the value of a class instance's field is stored? | class A {
public: int i;
};
A *a = new A();
How to get the address of a->i? I tried &a->i and also &(a->i) but those generate compile time errors:
"left of '.i' must have class/struct/union type"
| You have not provided the same code you tried to compile. Always copy and paste. The tells in your code are that you don't have a syntactically correct class declaration or variable declaration, and that your error message talks about ".i" when you've claimed you've only used a->i. Here's working code:
#include <stdio.... |
1,059,167 | 1,192,831 | MFC Control in a Qt Tab Widget | I'm working on a project that is using the Qt/MFC Migration Framework and I'm trying to reuse some existing MFC controls inside of a Qt dialog.
Does anyone know if it is possible to insert an MFC control (CDialog or CWnd) inside of a QTabWidget. Right now we're doing the opposite, we have an MFC dialog with a tab contr... | Seeing as you use QWinWidget, you must have come cross QWinHost? Simply use QWinHost as the pages for a QTabWidget:
HWND w = ...;
QTabWidget * tw = new QTabWidget;
QWinHost * wh = new QWinHost;
wh->setWindow( w );
tw->addTab( tr("Page with Windows Control"), wh );
|
1,059,200 | 1,059,219 | true isometric projection with opengl | I am a newbie in OpenGL programming with C++ and not very good at mathematics. Is there a simple way to have isometric projection?
I mean the true isometric projection, not the general orthogonal projection.
(Isometric projection happens only when projections of unit X, Y and Z vectors are equally long and angles betwe... | Try using gluLookAt
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
/* use this length so that camera is 1 unit away from origin */
double dist = sqrt(1 / 3.0);
gluLookAt(dist, dist, dist, /* position of camera */
0.0, 0.0, 0.0, /* where c... |
1,059,330 | 1,059,704 | why is set_intersection in STL so slow? | I'm intersecting a set of 100,000 numbers and a set of 1,000 numbers using set_intersection in STL and its taking 21s, where it takes 11ms in C#.
C++ Code:
int runIntersectionTestAlgo()
{
set<int> set1;
set<int> set2;
set<int> intersection;
// Create 100,000 values for set1
for ( int i = 0; i ... | On this ancient 3GHz Pentium 4, I get 2734 milliseconds for the entire runIntersectionTestAlgo function, in a debug build with optimizations disabled. I compiled with VS2008 SP1.
If I enable optimizations, I get 93 milliseconds.
Here's my code:
#include <set>
#include <algorithm>
using namespace std;
int runIntersect... |
1,059,372 | 1,059,393 | C++ code and objects from C? | Is there a simple way to work with C++ objects directly from C?
I want to expose some classes from C++ to C or to FFI(foreign function interface).
Sure, I can write a stuff like that:
class Foo{
....
};
void *make_foo(...){
Foo *ptr = new Foo(..)
return static_cast<void *>(ptr);
}
..
int *foo_method1(void *fooptr, ... | That, in general, is the simplest method.
Remember, too, that you'll need to use extern "C" on all of your C "wrapper" methods, as well.
|
1,059,432 | 1,059,533 | Call different classes in different time in same function | I just cannot imaginate a way to do a call to a function with genericity. I have a code which a have to call a function in two different classes in different moments.
I have A and B classes which I can access one time or other time. Or I access A or I access B. Not both in the same type.
I have code this program but I... | As you've written 'A' and 'B', you don't actually need the C class. By declaring your member functions "virtual" you are using run time polymorphism and this will result in the "correct" functions being called:
void foo (MyClass & mc) {
mc.a ();
}
int main () {
A a;
B b;
foo (a); // 'mc.a()' will call 'A::a... |
1,059,544 | 1,059,758 | SetThreadLocale and UTF8 | So I want to use SetThreadLocale to set a threads codepage to UTF8. Up to now, I've been using the second parameter of atl string conversion macros like "CT2A(szBUF, CP_UTF8)" to do this. But I want to be able to set the thread codepage once in the beginning with SetThreadLocale() and never have to use the second para... | SetThreadLocale expects a language identifier, but UTF-8 is not a language identifier - it's a Unicode encoding. One of the purposes of the land ID is to tell the system how to treat ANSI text in the range 128-255. Given a real language, its code page will be used when dealing with such characters. UTF-8, OTOH, is a co... |
1,059,545 | 2,412,962 | How to use stdext::hash_map where the key is a custom object? | Using the STL C++ hash_map...
class MyKeyObject
{
std::string str1;
std::string str2;
bool operator==(...) { this.str1 == that.str1 ... }
};
class MyData
{
std::string data1;
int data2;
std::string etcetc;
};
like this...
MyKeyObject a = MyKeyObject(...);
MyData b = MyData(...);
stdext::hash... | Try the following, worked for me in VS 2005. This is a solution for both VS2005 built-in hash_map type in stdext namespace as well as the boost unordered_map (preferred). Delete whichever you don't use.
#include <boost/unordered_map.hpp>
#include <hash_map>
class HashKey
{
public:
HashKey(const std::string& key)
... |
1,059,727 | 1,060,185 | C++ code in iPhone app | I'm trying to use a C++ library (CLucene) from my Cocoa Touch iPhone application using Xcode 3.1.3. Everything works fine when I run in the iPhone simulator, but things get strange when I run on device. It seems like pointers aren't being passed correctly from the Objective-C++ code (my app) to the C++ library (CLucene... | Disabling "Compile for Thumb" in the project's build settings fixes the problem.
|
1,059,824 | 1,060,029 | Interface/Superclass for Collections/Containers in c++ | I'm coming from the Java world and are building a small c++ program at the moment.
I have an object that does some work and then returns the result of the work as a list.
Now a day later i changed the behavior of the object to save the results in a set to avoid duplicates in the container. But I can't simply return th... | The concept of a container is enbodied by iterators.
As you have seen hard coding a specific type of container is probably not what you want. So make your class return iterators. You can then re-use the conatiners iterators.
class MyClass
{
private:
typedef std::list<int> Container;
public:
... |
1,059,838 | 1,059,938 | P/Invoke Struct with Pointers, C++ from C# | I'm attempt to call a C++ dll with a struct and function like
struct some_data{
int size,degree,df,order;
double *x,*y,lambda;
};
extern "C"{
__declspec(dllexport) double *some_func(some_data*);
}
from C#:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Seq... | Have you debugged into some_func? Try to windbg that program. Or use VS, but make sure to catch all exceptions and also enable mixed debugging.
|
1,060,337 | 1,060,929 | Why does my STL code run so slowly when I have the debugger/IDE attached? | I'm running the following code, using Visual Studio 2008 SP1, on Windows Vista Business x64, quad core machine, 8gb ram.
If I build a release build, and run it from the command line, it reports 31ms. If I then start it from the IDE, using F5, it reports 23353ms.
Here are the times: (all Win32 builds)
DEBUG, command l... | Running under a Microsoft debugger (windbg, kd, cdb, Visual Studio Debugger) by default forces Windows to use the debug heap instead of the default heap. On Windows 2000 and above, the default heap is the Low Fragmentation Heap, which is insanely good compared to the debug heap. You can query the kind of heap you are u... |
1,060,382 | 1,060,449 | Login and use rails from C++ | I need to use a rails app from C++. I say login in the title because that's one of my options.
As far as I see it, I either need to do the standard login, and keep track of a session or something in the C++ code, or use an API token of sorts, and just pass that on every URL and never actually create a session on the ra... | It may be lower-level than you're looking for, but I believe you should be able to accomplish this sort of thing with libcurl (and, potentially, libxml if you need an HTML or XML parser to handle return values).
|
1,060,483 | 1,060,681 | Dependency Injection in C++ | How do I implement dependancy injection in C++ explicitly without using frameworks or reflection?
I could use a factory to return a auto_ptr or a shared_ptr. Is this a good way to do it?
| Just use a shared_ptr to the service you need, and make a setter to it. E.g.:
class Engine;
class Car {
public:
void setEngine(shared_ptr<Engine> p_engine) {
this->m_engine = p_engine;
}
int onAcceleratorPedalStep(int p_gas_pedal_pressure) {
this->m_engine->setFuelValveIntake(p_gas_pedal_p... |
1,060,679 | 1,061,362 | Cross Platform Flash Player Embedding | I need to embed the Flash player in a native application (C++) in a cross platform way (at least Windows and Mac OSX). I need to allow the Flash gui to make calls back to the native application to do things that Flash normally can’t do (e.g. write to the file system, talk to devices, loading native image processing lib... | Another option is MDM Zinc. Win and OSX aren't 100% equal, and you should make sure it will do everything you need, but it may work for you.
|
1,060,991 | 1,067,029 | Compiling C++ program on Fedora | I'm having problems compiling an open source C++ project on Fedora. When I download and run the ./configure I eventually end up with....
.
.
.
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
./configure: line 15513: AX_CFLAGS_WARN_ALL: command... | I think your 'open source project' requires a later version of autoconf/aclocal
than the version installed.
'AX_CFLAGS _WARN _ALL', ..., 'AX _BOOST _BASE', are all autoconf macros which
would be correctly expanded if you had a newer version of autoconf.
|
1,061,060 | 1,062,290 | Embedding multiple, identically named resource (RC) files in a native DLL | For my application (an MMC snap-in) I need to create a single native DLL containing strings that are localized into different languages. In other words, if you were to inspect this DLL with Visual Studio, you would see multiple string tables, each associated with a different locale but containing the same string IDs.
T... | Yes. And No.
If you want multiple RC files you are going to have to leverage off the Operating systems support to have multiple resources in one file. In the resource editor, for each resource, you can set its locale AND the resource editor will allow you to have multiple resources with the same ID, as long as their lo... |
1,061,152 | 1,061,183 | C++ std::set comparator | This is the code:
struct comp
{
bool operator()(Reputation *one, Reputation *two)
{
if (one->Amount < 0 && two->Amount >= 0)
return false;
if (one->Amount >= 0 && two->Amount < 0)
return true;
if (one->Amount >= 0)
return one->Amount <= two->Amount;
... | You must define a relation that's irreflexive, just like < -- therefore, change the <= to < and the '>=' to '>' in the last couple of comparisons in your method. This is what VC++ is diagnosing.
Moreover, given a correctly coded, <-like operator, if two items a and b are such that a < b and b < a are both false, those ... |
1,061,169 | 1,063,308 | boost serialization vs google protocol buffers? | Does anyone with experience with these libraries have any comment on which one they preferred? Were there any performance differences or difficulties in using?
| I've played around a little with both systems, nothing serious, just some simple hackish stuff, but I felt that there's a real difference in how you're supposed to use the libraries.
With boost::serialization, you write your own structs/classes first, and then add the archiving methods, but you're still left with some ... |
1,061,246 | 1,061,252 | How can I check if a window has WS_VISIBLE to set? (or if is visible) | How can I do it? It's an external window, not from my program. Thanks
| Do you have an HWND to the window? If not, then you will need to obtain the window handle somehow, for example through FindWindow() (or FindWindowEx()).
Once you have the HWND to the window, call IsWindowVisible().
|
1,061,291 | 1,061,714 | does cdb/windbg have an equivalent to autoexp.dat? | I'd like to change the way some types are displayed using either 'dt' or '??' in a manner similar to how you can do that with autoexp.dat. Is there a way to do this?
For example, I have a structure something like this:
struct Foo
{
union Bar
{
int a;
void *p;
} b;
};
And I've got an array of... | I don't think there's anything as simple as autoexp.dat.
You have a couple potential options - you can write a simple script file with the debugger commands to dump the data structure in the way you want and use the "$<filename" command (or one of its variants). Combined with user aliases you can get this to be pretty... |
1,061,387 | 1,061,418 | Why do we use "type * var" instead of "type & var" when defining a pointer? | I'm relatively new to C++ (about one year of experience, on and off). I'm curious about what led to the decision of type * name as the syntax for defining pointers. It seems to me that the syntax should be type & name as the & symbol is used everywhere else in code to refer to the variable's memory address. So, to u... | C++ adopts the C syntax. As revealed in "The Development of the C Language" (by Dennis Ritchie) C uses * for pointers in type declarations because it was decided that type syntax should follow use.
For each object of [a compound type], there was already a way to mention the underlying object: index the array, call the... |
1,061,448 | 1,064,153 | Boost date add one day, non standard GMT string | In C++ what is the simplest way to add one day to a date in this format:
"20090629-05:57:43"
Probably using Boost 1.36 - Boost::date, Boost::posix_date or any other boost or std library functionality, I'm not interested in other libraries.
So far I came up with:
format the string (split date and time parts as string o... | That's pretty close to the simplest method I know of. About the only way to simplify it further would be using facets for the I/O stuff, to eliminate the need for string manipulation:
#include <iostream>
#include <sstream>
#include <locale>
#include <boost/date_time.hpp>
using namespace boost::local_time;
int main() ... |
1,061,543 | 1,061,555 | Whats the syntax to use boost::pool_allocator with boost::unordered_map? | I'm just experimenting with boost::pool to see if its a faster allocator for stuff I am working with, but I can't figure out how to use it with boost::unordered_map:
Here is a code snippet:
unordered_map<int,int,boost::hash<int>, fast_pool_allocator<int>> theMap;
theMap[1] = 2;
Here is the compile error I get:
Erro... | It looks like you are missing a template parameter.
template<typename Key, typename Mapped, typename Hash = boost::hash<Key>,
typename Pred = std::equal_to<Key>,
typename Alloc = std::allocator<std::pair<Key const, Mapped> > >
The fourth parameter is the predicate for comparison, the fifth is the allocato... |
1,061,578 | 1,061,591 | Method to return to beginning of function | Does C++ have any type of utility to return to the beginning of a function after a function call? For example, example the call to help() in the calculate function.
void help()
{
cout << "Welcome to this annoying calculator program.\n";
cout << "You can add(+), subtract(-), multiply(*), divide(/),\n";
co... | You can use goto, but the moment you do that consider yourself over. It's considered bad practice and good uses of it are rare and far apart.
I think what you're looking for is continue:
void do_calculate(void)
{
while (true)
{
cout << prompt;
Token t = ts.get();
if (t.kind == help_user... |
1,061,611 | 1,061,617 | C++ - Calling a function inside a class with the same name as the class | I was trying to write up a class in c++, and I came across a rather odd problem: calling outside functions inside of a class that have the same name as the class. It's kinda confusing, so here's an example:
void A(char* D) {
printf(D);
}
class A
{
public:
A(int B);
void C();
};
A::A(int B) {
// something her... | ::A("Hello, world.");
should work fine. Basically it is saying "use the A found in the global namespace"
|
1,061,634 | 1,061,660 | How do I know who holds the shared_ptr<>? | I use boost::shared_ptr in my application in C++. The memory problem is really serious, and the application takes large amount of memory.
However, because I put every newed object into a shared_ptr, when the application exits, no memory leaking can be detected.
There must be something like std::vector<shared_ptr<> > po... | You can't know, by only looking at a shared_ptr, where the "sibling pointers" are. You can test if one is unique() or get the use_count(), among other methods.
|
1,061,726 | 1,062,393 | Public virtual function derived private in C++ | I was trying to figure out what happens when a derived class declares a virtual function as private. The following is the program that I wrote
#include <iostream>
using namespace std;
class A
{
public:
virtual void func() {
cout<<"A::func called"<<endl;
}
private:
};
class B:public A
{
p... | The behavior is correct. Whenever you declare your function as "virtual", you instruct the compiler to generate a virtual call, instead of the direct call to this function. Whenever you override the virtual function in the descendant class, you specify the behavior of this function (you do not change the access mode fo... |
1,061,889 | 1,062,378 | lock-free memory reclamation with 64bit pointers | Herlihy and Shavit's book (The Art of Multiprocessor Programming) solution to memory reclamation uses Java's AtomicStampedReference<T>;.
To write one in C++ for the x86_64 I imagine requires at least a 12 byte swap operation - 8 for a 64bit pointer and 4 for the int.
Is there x86 hardware support for this and if not, a... | Yes, there is hardware support, though I don't know if it is exposed by C++ libraries. Anyway, if you don't mind doing some low-level unportable assembly language trickery - look up the CMPXCHG16B instruction in Intel manuals.
|
1,061,903 | 1,061,936 | C++ : How to write a const_iterator? | I've written my own container template with an iterator. How do I implement const_iterator?
template <class T>
class my_container {
private:
...
public:
my_container() : ... { }
~my_container() { }
class iterator : public std::iterator<std::bidirectional_iterator_tag, T> {
public: ...
| The only difference should be that when you de-reference a const iterator you get a const reference rather than a reference to the object in the container.
|
1,061,966 | 1,062,034 | Expression: String iterator not dereferencable | I'm having a hard time using std::string::iterators in C++. This code compiles fine (still not getting correct output, but that's my fault: TODO, fix algorithm) in Dev-C++, and I don't get runtime errors. The error is with Visual Studio Express 2008 C++, where I'm getting an error pointing to < xstring>: "Expression: s... | Firstly, use operator!=() on iterators, not operator<():
while (it != sentence.end())
Secondly, this is backwards: while (*it != ' ' && it != sentence.end())
You do something with the iterator, than check if the iterator is valid. Rather, you should check if it's valid first:
while (it != sentence.end() && *it != ' '... |
1,062,156 | 1,067,627 | Error while opening shared object: SunGrid Engine | My application uses the Sun N1 grid engine through the API DRMAA present as shared object libdrmaa.so
.
I am using dlopen and dlsym to acess functions of the library. That works fine. Now if I try to link
it form command line the executable is built but executing it gives the error " Cannot open shared object file".
C... | Your question and answer are both very confused: if you can link your executable directly against libdrmaa.so, then there is absolutely no good reason to also dlopen that same library (and presumably call dlsym() on its handle as well).
|
1,062,198 | 1,062,265 | C++ library with a Java-like API | Hoping that anybody here knows about a good one: I'm looking for a (free to use) C++ library with a class hierarchy and methods resembling the Java API, with at least the I/O & networking part if it, specifically HTTP handling.
I work mainly with C & Java, but for this particular project C++ is recommended, so I though... | Qt is IMHO very java like. I.e. they prefer Java-Style Iterators over the STL ones. Qt includes networking (examples) and much other stuff (like scripting via javascript)
|
1,062,306 | 1,062,346 | SetCurrentDirectory in multi-threaded application | I understand SetCurrentDirectory shouldn't be used in a multithreaded application since the current directory is shared between all threads in the process.
What is the best approach to setting the directory with this in mind.
It can mostly be avoided setting the directory by including the full pathname when opening fil... | I've encountered this problem before.
Any object that needs the concept of a current directory to support relative paths or searching (e.g. a build tool) has a member property that it maintains with its "current" path, then build the full path to open/create/search.
The initial value for CurrentPath can be retrieved on... |
1,062,478 | 1,074,661 | QTreeView - Sort and Filter a model | I am trying to create a QTreeView which displays some sorted information. To do this I use a QSortFilterProxyModel between the view and my model.
The problem is that I want to limit the number of rows to the first n rows (after sorting). The filter function from the model receives the original sourceRow so I cannot use... | After trying a number of overcomplicated ways to solve this I've done a small hack for my problem: after I insert/remove a row I call setRowHidden to hide the first n rows.
This is not the most elegant solution and is particular for my needs, but I am unable to find a better alternative.
I like to mention that on gtk, ... |
1,062,601 | 1,062,647 | How does the C++ STL vector template store its objects in the Visual Studio compiler implementation? | I am extending the Visual Studio 2003 debugger using autoexp.dat and a DLL to improve the way it displays data in the watch window. The main reason I am using a DLL rather than just the basic autoexp.dat functionality is that I want to be able to display things conditionally. e.g. I want to be able to say "If the name ... | The elements in a standard vector are allocated as one contiguous memory chunk.
You can get a pointer to the memory by taking the address of the first element, which can be done is a few ways:
std::vector<int> vec;
/* populate vec, e.g.: vec.resize(100); */
int* arr = vec.data(); // Method 1, C++11 and beyond.
int* ... |
1,062,690 | 1,067,764 | QtCreator performance on Windows | I've finally managed to run the QtCreator debugger on Windows after struggling with the Comodo Firewall incompatibilities.
I was hoping to switch from an older version of Qt and Visual C++ to the newest version of Qt and QtCreator, but the debugger performance is atrocious.
I have created a simple GUI with one window ... | Yesterday I built a copy of the Qt 4.5.2 libraries using MSVC 2008 and am using the QtCreator 1.2 MS CDB (Microsoft Console Debugger) support. It seems much faster than gdb. Building Qt for MSVC takes a few hours, but it might be worth trying.
Also, that means smaller Qt DLLs and EXEs as the MS compiler/linker is muc... |
1,062,748 | 1,062,809 | How do I handle combinations of behaviours? | I am considering the problem of validating real numbers of various formats, because this is very similar to a problem I am facing in design.
Real numbers may come in different combinations of formats, for example:
1. with/without sign at the front
2. with/without a decimal point (if no decimal point, then perhaps numbe... |
In OO design, you would normally
allocate a class for each number
format (e.g. in this case, we have 8
classes), and each class would have a
separate validation function.
No no no no no. At most, you'd have a type for representing Numeric Input (in case String doesn't make it); another one for Real Number (in... |
1,062,861 | 1,062,878 | ios::nocreate error while compiling a C++ code | While, compiling a package, written in C++ on RHEL 5.0. I am getting the following error.
> error: nocreate is not a member of std::ios
The source-code corresponds to:
ifstream tempStr(argv[4],ios::in|ios::nocreate);
I have tried
#g++ -O -Wno-deprecated <file.cpp> -o <file>
as well as:
#g++ -O -o <file>
Please ... | ios::nocreate is not part of standard C++ - what are you expecting it to do?
Edit: From a Google, it seems like it was intended to prevent the file being created if it doesn't already exist. This is the default for ifstreams anyway, so you can just say:
ifstream f( filename );
if ( ! f.is_open() ) {
// open failed ... |
1,062,965 | 1,064,831 | VirtualAlloc failing on certain configurations of hdd | For some reason on my application when running on some configuration of hard disk (RAID, random partitions, through a separate IDE controller, not on the operating systems partition), VirtualAlloc returns null with the GetLastError code of ERROR_INVALID_PARAMETER.
The only parameter apart from the flags (MEM_COMMIT | ... | Issue was to do with DeviceIoControl when trying to return IOCTL_DISK_GET_DRIVE_GEOMETRY seemed to be returning complete garbage when using anything other than the primary hdd, I solved this by using GetDiskFreeSpace instead to get the sector information and is all working fine
obviously finding out why IOCTL_DISK_G... |
1,063,133 | 1,065,150 | Usage of volatile specifier in C/C++/Java | While going through many resources on multithreaded programming, reference to volatile specifier usually comes up.
It is clear that usage of this keyword is not a reliable way to achieve synchronization between multiple threads atleast in C/C++ and Java (versions 1.4 and earlier).
Here is what wikipedia lists (without ... | Since you're interested in those usage cases, I'll explain the first one. Note that this applies from a c/c++ perspective, not sure how it plays into java, although I suspect in general volatile in c/c++ and java are used for completely different cases.
Memory mapped devices are peripherals which the processor communic... |
1,063,147 | 1,063,191 | Select() not Working in thread | I have to monitor a serial port and process its data. As a test program I was using select for just one port. The run function is as follows:
void <ProtocolClass>::run()
{
int fd = mPort->GetFileDescriptor();
fd_set readfs;
int maxfd=1;
int res;
FD_ZERO(&readfs);
FD_SET(fd,&readfs);
struct t... | i think i know what's the problem.
FD_ZERO(&readfs);
FD_SET(fd,&readfs);
The above lines should be inside the while loop.
Because, select call will reset the 'fd' bit position in the readFs structure. So, the next time when select is called, it does know what while file descriptors to poll, as all are reset here.
Th... |
1,063,156 | 1,065,821 | Is it possible to add CMFCToolBar to a dialog? | I just tryed the standard way for adding CToolbar to a dialog on the new CMFCToolBar. But it doesn't work. Befor I dip into the new implementation, I want to know if it actually possible?
| I'm not sure what you mean by "the standard way", but you can certainly do it programatically:
// In MyDlg.h
class CMyDlg : public CDialog
{
...
CMFCToolBar m_ToolBar;
...
};
// In MyDlg.cpp
BOOL CMyDlg::OnInitDialog()
{
...
if( m_ToolBar.Create( this, AFX_DEFAULT_TOOLBAR_STYLE, 100 ) )
{
m_ToolBar... |
1,063,453 | 1,063,492 | How can I display the content of a map on the console? | I have a map declared as follows:
map < string , list < string > > mapex ; list< string > li;
How can I display the items stored in the above map on the console?
| Well it depends on how you want to display them, but you can always iterate them easily:
typedef map<string, list<string>>::const_iterator MapIterator;
for (MapIterator iter = mapex.begin(); iter != mapex.end(); iter++)
{
cout << "Key: " << iter->first << endl << "Values:" << endl;
typedef list<string>::const_i... |
1,063,733 | 1,063,985 | QtCreator project with multiple libs and one exe | Like I said in a previous question, I'm planning on porting a Qt project from VC++ to QtCreator.
The project consists of 4 subprojects: 3 of them are libs and the last one makes the exe.
The subprojects are layered, meaning that each layer has compile and link time dependencies to the layers beneath it.
The files are o... | After working on the problem some more, I remembered that for the GCC tool chain the order of the linker parameters is important.
Reversing the LIBS entries did the trick.
|
1,063,809 | 1,063,893 | Aligned and unaligned memory accesses? | What is the difference between aligned and unaligned memory access?
I work on an TMS320C64x DSP, and I want to use the intrinsic functions (C functions for assembly instructions) and it has
ushort & _amem2(void *ptr);
ushort & _mem2(void *ptr);
where _amem2 does an aligned access of 2 bytes and _mem2 does unaligned a... | An aligned memory access means that the pointer (as an integer) is a multiple of a type-specific value called the alignment. The alignment is the natural address multiple where the type must be, or should be stored (e.g. for performance reasons) on a CPU. For example, a CPU might require that all two-byte loads or stor... |
1,064,248 | 1,064,277 | Correct way to initialize an object with exception throwing constructor | This seems to be a trivial question but I got hung on it for a few hours now (maybe too much Java killed my C++ braincells).
I have created a class that has the following constructor (i.e. no default constructor)
VACaptureSource::VACaptureSource( std::string inputType, std::string inputLocation ) {
if( type == "" |... | What about using a pointer (or some RAII version thereof)?
VACaptureSource* input = NULL;
try {
input = new VACaptureSource(...);
} catch(...) {
//error handling
}
//And, of course, at the end of the program
delete input;
|
1,064,325 | 1,064,388 | Why not use pointers for everything in C++? | Suppose that I define some class:
class Pixel {
public:
Pixel(){ x=0; y=0;};
int x;
int y;
}
Then write some code using it. Why would I do the following?
Pixel p;
p.x = 2;
p.y = 5;
Coming from a Java world I always write:
Pixel* p = new Pixel();
p->x = 2;
p->y = 5;
They basically do the same th... | Yes, one is on the stack, the other on the heap. There are two important differences:
First, the obvious, and less important one: Heap allocations are slow. Stack allocations are fast.
Second, and much more important is RAII. Because the stack-allocated version is automatically cleaned up, it is useful. Its destructo... |
1,065,011 | 1,065,191 | Why is this boost header file not included | I'm building my c++ program with cmake on a Mac. The compiler gives me following Error:
error: boost/filesystem.hpp: No such file or directory
The line that triggers the error is the following:
#include "boost/filesystem.hpp"
or
#include <boost/filesystem.hpp>
Which of the above I use doesn't changed the Error
But i... | First of all use
FIND_PACKAGE(Boost REQUIRED)
rather than
FIND_PACKAGE(Boost)
This way cmake will give you a nice error message if it doesn't find it, long before any compilations are started. If it fails set the environment variable BOOST_ROOT to /opt/local (which is the install prefix).
Additionally you will hav... |
1,065,054 | 1,065,171 | C++ Process Management | Is there a well-known, portable, good library for C++ process management?
I found a promising library called Boost.Process, but it's only a candidate for inclusion in the Boost library. Has anyone use this? Does anyone know why it isn't a part of Boost?
| How much management do you need? Just fork/exec? IPC? Resource management? Security contexts and process isolation?
I haven't used the Boost.Process library. However, I do know that getting included in Boost is a rather difficult affair. Boost recently accepted a futures library that had already been approved as ... |
1,065,211 | 1,066,423 | How can I use a class from a header file in a source file using extern but not #include? | If I have a class in outside.h like:
class Outside
{
public:
Outside(int count);
GetCount();
}
How can I use it in framework.cpp using the extern keyword, where I need to instantiate the class and call GetCount?
Edit:
#include is not allowed.
| Just to clarify. It is impossible to extern the class:
class Outside
{
public:
Outside(int count);
GetCount();
}
But, once you have the class available in framework.cpp, you CAN extern an object of type Outside. You'll need a .cpp file declaring that variable:
#include "outside.h"
Outside outsid... |
1,065,623 | 1,069,085 | Compile Cygwin project in Eclipse | I have a c++ Project that was compiled with the cygwin toolchain, now I want to use Eclipse to compile and test it.
If I create a project (cygwin toolchain is set in the options) I get the error:
make: *** No rule to make target `all'. 7wWin line 0 C/C++ Problem
In Cygwin I use:
cd $BUILDDIR
make
make install
... | Check the following pages:
http://homepage.cs.uri.edu/courses/fall2007/csc406/Handouts/eclipseTutorial.pdf
http://wikimix.blogspot.com/2006/11/using-eclipse-as-c-development_05.html
http://www.benjaminarai.com/benjamin_arai/index.php?display=/eclipsecygwingcc.php
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.