question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,412,521 | 2,412,617 | Is there a C++ dependency index somewhere? | When trying new software and compiling with the classic ./configure, make, make install process, I frequently see something like:
error: ____.h: No such file or directory
Sometimes, I get really lucky and apt-get install ____ installs the missing piece and all is well. However, that doesn't always happen and I end u... | You can also use "auto-apt ./configure" (on Ubuntu, and probably also on Debian?) and it will attempt to download dependencies automatically.
|
2,412,608 | 2,412,651 | g++: const discards qualifiers | why do I get a discard qualifiers error:
customExc.cpp: In member function ‘virtual const char* CustomException::what() const’:
customExc.cpp: error: passing ‘const CustomException’ as ‘this’ argument of ‘char customException::code()’ discards qualifiers
on the following code example
#include <iostream>
class Custom... | CustomException::what calls CustomException::code. CustomException::what is a const method, as signified by the const after what(). Since it is a const method, it cannot do anything that may modify itself. CustomException::code is not a const method, which means that it does not promise to not modify itself. So Cus... |
2,412,667 | 2,412,837 | Seg Fault when using std::string on an embedded Linux platform | I have been working for a couple of days on a problem with my application running on an embedded Arm Linux platform. Unfortunately the platform precludes me from using any of the usual useful tools for finding the exact issue. When the same code is run on the PC running Linux, I get no such error.
In the sample below, ... | Maybe you're using a single-threaded version of the standard library, including the new and delete operators?
Those objects are being constructed within the guards of your mutex, but are destructed outside those bounds, so the destructors might be stepping on each other. One quick test would be to put scoping brackets... |
2,412,718 | 2,412,752 | Declare float or cast float? | I've started to learn C++ using "C++ Primer by Stephen Prate" and I'm currently trying to complete one of the exercises. I am wondering if I should declare arc_to_minute & arc_to_degree as float or cast them as float as I've done already. Any tips welcome!
#include <iostream>
int main()
{
using namespace std;
... | Make them floats, there's no reason for them to be integers when all your calculations are done in floating point:
const float arc_to_minute = 60.0f;
const float arc_to_degree = 60.0f;
Keep in mind in a constant-value case the cast will be done at compile-time anyway, so this is purely a design choice, with no perform... |
2,412,792 | 2,413,210 | Multi-Threaded MPI Process Suddenly Terminating | I'm writing an MPI program (Visual Studio 2k8 + MSMPI) that uses Boost::thread to spawn two threads per MPI process, and have run into a problem I'm having trouble tracking down.
When I run the program with: mpiexec -n 2 program.exe, one of the processes suddenly terminates:
job aborted:
[ranks] message
[0] terminated... | you have to use thread safe version of mpi runtime.
read up on MPI_Init_thread.
|
2,412,838 | 2,415,439 | Unable to access tables created with sqlite3 from a program using the C API | I generate an sqlite3 database file (call it db.sl3; invoked interactively as $ sqlite3 db.sl3 from a shell) from within the sqlite3 commandline program, for instance
create table people (
id integer,
firstname varchar(20),
lastname varchar(20),
phonenumber ... | By default sqlite3_open will create the database if it does not exist (equivalent with calling sqlite3_open_v2 with flags=SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) - and rc will be SQLITE_OK.
I've tried this test program against a database created using sqlite3 and each time (existing db with people table: full path,... |
2,412,941 | 2,413,033 | QT 2d list causing segfault | I've got a program that worked until recently. The offending code is shown here:
void writeTimeInfo(fitsfile *fptr, QList<QList<double> > &in)
{
double data[in.size() * in[0].size()];
long naxes[2];
int status = 0;
naxes[1] = in.size();
naxes[0] = in[0].size();
for (int i=0; i<naxes[1]; i++)
{
for (int j=0; ... | An array of 515 * 1508 doubles is roughly 6MB -- a lot for the stack. This is probably a stackoverflow. Try setting the stack limit by using --stack option of ld to ~10 MB (if possible) and test with the value of 515 * 2480.
On Windows, using VS2010 Beta, the following crashes the stack:
int main() { double x[ 515 * 15... |
2,412,971 | 2,412,984 | How can I find the real size of my C++ class? | I'm working on a homework assignment in which I'm required to use char arrays instead of strings and qsort/bsearch. In my call to bsearch below, I know I'm passing the wrong size of Entry, but I'm not sure how to get the real size, and my compareEntries function is therefore not finding the right objects.
Can anyone h... | Why doesn't sizeof(Entry) work?
Changed again -- I think the size should be the size of the pointer....
EntryPtr tmp = new Entry("");
tmp->Word = word;
EntryPtr result = (EntryPtr) bsearch(tmp, m_entries,
m_numEntries, sizeof(EntryPtr), Dictionary::compareEntries);
|
2,413,034 | 2,413,410 | Problem to convert string binary (64 bits) to decimal (c++ in iphone) | I have a problem converting a string binary to a decimal
I was using bitset
bitstring ="1011010001111111";
unsigned long binToDec( string bitstring){
bitset<32> dec (bitstring);
return dec.to_ulong();
}
All of this works fine, but !! the problem comes when i try to do the same with a bits string with more of ... | I've just put together this and it seems to work with your example, I haven't tested any bigger values, compared result with calculator.
Outputs:
64497387062899839
Code:
#include <iostream>
#include <limits>
using namespace std;
unsigned long long convert(string& bits)
{
if (bits.length() > (size_t)numeric_limit... |
2,413,172 | 2,413,269 | Cross platform C++ code architecture | I'm having a bit of a go at developing a platform abstraction library for an application I'm writing, and struggling to come up with a neat way of separating my platform independent code from the platform specific code.
As I see it there are two basic approaches possible: platform independent classes with platform spec... | I'm using platform neutral header files, keeping any platform specific code in the source files (using the PIMPL idiom where neccessary). Each platform neutral header has one platform specific source file per platform, with extensions such as *.win32.cpp, *.posix.cpp. The platform specific ones are only compiled on the... |
2,413,342 | 2,413,392 | OpenCV: Reading a YAML file into a CvMat structure | Using OpenCV, saving a CvMat structure into a YAML file on the disk is easy with
CvMat* my_matrix = cvCreateMat( row_no, col_no, CV_32FC1 );
cvSave("filename.yml", my_matrix);
However, I couldn't find an easy way to read the saved files back from the disk. Is there function in OpenCV that can handle this and create ... | CvMat* my_matrix;
my_matrix = (CvMat*)cvLoad("filename.yml");
seems to do the trick!
|
2,413,533 | 2,413,649 | How should I go about generating every possible map<char, char> combination from map<char, vector<char> >? | I am looking to take a map<char, vector<char> > and generate each possible map<char, char> from it.
I understand this may use a sizeable amount of memory and take a bit of time.
Each map<char, char> needs to contain every letter a-z, and be mapped to a unique a-z character. ie.
ak
bj
cp
dy
ev
fh
ga
hb
ir
jq
kn
li
mx
nc... | I guess I'd hope that I don't need them all to exist simultaneously. Then I could:
1) Create the first map by assigning the first possible element to each letter:
for (char c = 'a'; c <= 'z'; ++c) { // yes, I assume ASCII
new_map[c] = old_map[c][0];
}
int indexes[26] = {0};
2) Create the remaining maps in turn by ... |
2,413,786 | 2,413,815 | Using for_each and boost::bind with a vector of pointers | I have a vector of pointers. I would like to call a function for every element, but that function takes a reference. Is there a simple way to dereference the elements?
Example:
MyClass::ReferenceFn( Element & e ) { ... }
MyClass::PointerFn( Element * e ) { ... }
MyClass::Function()
{
std::vector< Element * > ele... | You could use boost::indirect_iterator:
std::for_each( boost::make_indirect_iterator(elements.begin()),
boost::make_indirect_iterator(elements.end()),
boost::bind( &MyClass::ReferenceFn, boost::ref(*this), _1 ) );
That will dereference the adapted iterator twice in its operator*.
|
2,414,095 | 2,414,125 | How to hide specific type completely using typedef? | I have a quick question about encapsulating specific types with typedef. Say I have a class Foo whose constructor takes a certain value, but I want to hide the specific type using typedef:
class Foo {
public:
typedef boost::shared_ptr< std::vector<int> > value_type;
Foo(value_type val) : val_(val) {}
private:
... | Various solutions:
Foo::value_type val(new Foo::value_type::element_type());
// least change from your current code, might be too verbose or too
// coupled to boost's smart pointer library, depending on your needs
Foo::value_type val(new Foo::element_type());
// add this typedef to Foo: typedef value_type::element_typ... |
2,414,155 | 2,414,208 | Getting input from a file in C++ | I am currently developing an application, which gets the input from a text file and proceeds accordingly. The concept is the input file will have details in this fomat
A AND B
B OR C
Each and every line will be seperated by a blank space and the input must be taken from the text file and processed by logic.... | Reading input a line at a time is normally done with std::getline, something like this:
std::string line;
std::ifstream infile("filename");
while (std::getline(line, infile))
// show what we read
std::cout << line << "\n";
If you're having trouble with things like this, you might consider looking for a (bette... |
2,414,261 | 2,415,084 | What is the current modern term for "Multi-byte Character Set" | I used to be confusing quite a while :
Confusion on Unicode and Multibyte Articles
After reading up the comments by all contributors, plus :
Looking at an old article (Year 2001) : http://www.hastingsresearch.com/net/04-unicode-limitations.shtml, which talk about unicode :
being a 16-bit character definition
allowin... | http://en.wikipedia.org/wiki/Multi-byte_character_set
MBCS is a term used to denote a class of character encodings with characters that cannot be represented with a single byte, hence multi-byte character set. In order to properly decode a string in this format, you need a codepage that tells you various byte combinati... |
2,414,359 | 2,457,919 | Microsecond resolution timestamps on Windows | How do I get microsecond resolution timestamps on Windows?
I am loking for something better than QueryPerformanceCounter and QueryPerformanceFrequency (these can only give you an elapsed time since boot and are not necessarily accurate if they are called on different threads - that is, QueryPerformanceCounter may retur... | I believe this is still useful: System Internals: Guidelines For Providing Multimedia Timer Support.
It does a good job of explaining the various timers available and their limitations. It might be that your archenemy will not so much be resolution, but latency.
QueryPerformanceCounter will not always run at CPU speed.... |
2,414,399 | 2,414,432 | Problem linking to a DLL from C++ console application | I have a console application in C++. I need to access a functionality from a C++ DLL. How do I link the DLL from my console application?
Please help me in this regard.
Thanks,
Rakesh.
| It depends on whether you are using load-time or run-time dynamic linking.
With load-time dynamic linking, you simply link against the import library for the DLL and make sure the DLL is in the right location when you run. With run-time dynamic linking, you need to use LoadLibrary and GetProcAddress to make calls in... |
2,414,463 | 2,414,469 | Application launch from c command in window OS | I want to make an console application of c which can run other applications (exe files). Kindly guide me how can I make it possible so that from my c code i can run other executable files in window OS.
| You can use the CreateProcess Windows API function.
|
2,414,477 | 2,414,503 | Stl Set find an item c++ | I have a set where i want to find items in it. Right now i have global objects that i am using to store my finds - (ItemSetMap allMusicByBand)
I would like to get away from this and just search the sets directly.
All the cd info are stored in the private section - (ItemSet allCDS;)
here is the library.cpp -
the commen... | The simplest way to do it would be this:
const ItemSet* Library::musicByBand(const string& band) const
{
ItemSet* bandMusic = new ItemSet();
for (ItemSet::const_iterator i = allCDs.begin(); i != allCDs.end(); ++i)
{
if ((*i)->getBand() == band) {
bandMusic->insert(*i);
}
}
retur... |
2,414,478 | 2,414,490 | Escaping an apostrophe in a character literal | Could you please tell me how can one escape an apostrophe.
I need it to process non apostrophe characters through file operations so when I encounter an apostrophe(') I can't just give ch!='''. It doesn't work. Could you please tell me the right format. Thank you..:)
| Use \', for example:
if ( ch != '\'' )
\' is an escape sequence for the apostrophe.
Google for "escape sequence" to know more about it.
|
2,414,561 | 2,414,570 | Why some libraries must implement basic data structure? | Some open source libraries have tendency to re implement basic structures like string, list, stack, queue...
Why don't they use stl library? Is stl not good enough?
| Exposing STL types in headers can, in some cases, lead to nasty, nasty link times. On large projects, that can be sufficient reason to "hide" them behind a proprietary-looking API.
|
2,414,616 | 2,414,661 | How to make script/program to make it so an application is always running? | I have a simple .exe that needs to be running continuously.
Unfortunately, sometimes it crashes unexpectedly, and there's nothing that can be done for this.
I'm thinking of like a C# program that scans the running application tree on a timer and if the process stops running it re-launches it... ? Not sure how to do th... | It's fairly easy to do that, but the "crashes unexpectedly, and there's nothing that can be done for this" sounds highly suspect to me. Perhaps you mean the program in question is from a third party, and you need to work around problems they can't/won't fix?
In any case, there's quite a bit of sample code to do exactly... |
2,414,828 | 2,414,852 | Get path to My Documents | From Visual C++, how do I get the path to the current user's My Documents folder?
Edit:
I have this:
TCHAR my_documents[MAX_PATH];
HRESULT result = SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, my_documents);
However, result is coming back with a value of E_INVALIDARG. Any thoughts as to why this ... | It depends on how old of a system you need compatibility with. For old systems, there's SHGetSpecialFolderPath. For somewhat newer systems, there's SHGetFolderPath. Starting with Vista, there's SHGetKnownFolderPath.
Here's some demo code that works, at least on my machine:
#include <windows.h>
#include <iostream>
#inc... |
2,414,872 | 2,415,198 | IPhone compilation of ported code problems: calling a static templated function that's inside a templated class == fail | template<typename T> struct AClass
{
public:
template<typename T0>
static void AFunc()
{}
};
template<typename T>
void ATestFunc()
{
AClass<T>::AFunc<int>();
}
this works on other platforms, but not on the iPhone I get an error " expected primary-expression before 'int' " on the line where I call ... | try changing the line AClass<T>::AFunc<int>() to AClass<T>::template AFunc<int>();
|
2,415,082 | 2,415,088 | When to use recursive mutex? | I understand recursive mutex allows mutex to be locked more than once without getting to a deadlock and should be unlocked the same number of times. But in what specific situations do you need to use a recursive mutex? I'm looking for design/code-level situations.
| For example when you have function that calls it recursively, and you want to get synchronized access to it:
void foo() {
... mutex_acquire();
... foo();
... mutex_release();
}
without a recursive mutex you would have to create an "entry point" function first, and this becomes cumbersome when you have a set o... |
2,415,153 | 2,415,167 | How often do you declare your functions to be const? | Do you find it helpful?
| Every time You know that method won't change state of the object you should declare it to be constant.
It helps reading your code. And it helps when you try to change state of the object - compiler will stop you.
|
2,415,373 | 2,415,593 | Small block allocator on Linux (or RedHat Linux) to avoid memory fragmentation | I know that there is an allocator for user applications than handles lots of small block allocation on HP-UX link text and on Windows XP Low-fragmentation Heap. On HP-UX it is possible to tune the allocator and on Windows XP it considers block of size less than 16 K as small.
My problem is that I can't find any informa... | Redhat Linux or any Linux based distributions mostly use DL-Malloc (http://gee.cs.oswego.edu/dl/html/malloc.html).
For user applications as Kirill pointed out, better to use separate memory allocators if fragmentation is more because of smaller blocks.
If the user application is small, you can try using C++ placement n... |
2,415,927 | 2,416,048 | ITERATOR LIST CORRUPTED in std::string constructor | The code below compiled in Debug configuration in VS2005 SP1 shows two messages with “ITERATOR LIST CORRUPTED” notice.
Code Snippet
#define _SECURE_SCL 0
#define _HAS_ITERATOR_DEBUGGING 0
#include <sstream>
#include <string>
int main()
{
std::stringstream stream;
stream << "123" << std::endl;
std::string str = ... | What @dirkgently said in his edit.
Apparently, some code for std::string is located in the runtime dll, in particular the macro definition does not take effect for the constructor an the code for iterator debugging gets executed. You can fix this by linking the runtime library statically.
I would consider this a bug, t... |
2,415,989 | 2,417,589 | Is it possible to compact the VC++ runtime heap? | Can I have the same effect as with HeapCompact() for the Visual C++ runtime heap? How can I achieve that?
| You can get a HANDLE for the CRT heap using _get_heap_handle, then call HeapCompact on it. Not sure whether this is supported/stable as I have not tried this myself. I imagine you would want to call HeapCompact in serialized mode to have any chance of this working.
If you are going to this trouble just call HeapSetIn... |
2,416,033 | 2,416,142 | Creating csv files in ObjC | Is it possible or any library available for creating .csv file in ObjC ?
Thanks
| A CSV file is a text file of comma seperated values.
You could write an a routine that loops through values adding each one to a text file (or even add the values to a string?). After each field, add the ',' character. At the end of each row, add a new line. The first row can be the field titles.
E.g.
Year,Make,Model
... |
2,416,091 | 2,416,259 | How applications can be protected from errors in DLL module | I have DLL and application that will call some function in this dll. For example...
DLL function:
char const* func1()
{
return reinterpret_cast<char const*>(0x11223344);
}
Application code:
func1 = reinterpret_cast<Func1Callback>(::GetProcAddress(hDll, "func1"));
blablabla
char const* ptr = func1();
cout << pt... | Since the DLL can do anything your program could do the only reliable way is to load it into a separate worker lightweight process and once anything bad happens just restart the process. You'll need some protocol to pass data into the worker process and receive results.
|
2,416,255 | 2,416,399 | Destruction of string temporaries in thrown exceptions | Consider the following code:
std::string my_error_string = "Some error message";
// ...
throw std::runtime_error(std::string("Error: ") + my_error_string);
The string passed to runtime_error is a temporary returned by string's operator+. Suppose this exception is handled something like:
catch (const std::runtime_er... | As a temporary object (12.2), the result of the + will be destroyed as the last step in the evaluation of the full-expression (1.9/9) that contains it. In this case the full-expression is the throw-expression.
A throw-expression constructs a temporary object (the exception-object) (15.1) (std::runtime_error in this cas... |
2,416,653 | 2,497,534 | Tuples of unknown size/parameter types | I need to create a map, from integers to sets of tuples, the tuples in a single set have the same size. The problem is that the size of a tuple and its parameter types can be determined at runtime, not compile time. I am imagining something like:
std::map<int, std::set<boost::tuple> >
but not exctly sure how to exactl... | The purpose of boost::tuple is to mix arbitrary types. If, as you say,
I am only inserting integers
then you should use map< int, set< vector< int > > >. (If I were you, I'd throw some typedefs at that.)
To answer the original question, though, boost::tuple doesn't allow arbitrary types at runtime. boost::any does. H... |
2,416,932 | 2,416,954 | Virtual Inheritance : Base Ctor not calling in Most Derived Class? | class Base
{
public:
Base(){}
Base(int k):a(k)
{
}
int a;
};
class X:virtual public Base
{
public:
X():Base(10){}
int x;
};
class Y:virtual public Base
{
public:
Y():Base(10){}
int y;
};
class ... | Because you used the virtual keyword - that's exactly what it does.
You have to explicitly initialize Base in the initializer list of Z in order to disambiguate between the initialization in X and the initalization in Y.
|
2,417,195 | 2,417,536 | What's the shortest code to write directly to a memory address in C/C++? | I'm writing system-level code for an embedded system without memory protection (on an ARM Cortex-M1, compiling with gcc 4.3) and need to read/write directly to a memory-mapped register. So far, my code looks like this:
#define UART0 0x4000C000
#define UART0CTL (UART0 + 0x30)
volatile unsigned int *p;
p = UART0CTL... | I'd like to be a nitpick: are we talking C or C++ ?
If C, I defer to Chris' answer willingly (and I'd like the C++ tag to be removed).
If C++, I advise against the use of those nasty C-Casts and #define altogether.
The idiomatic C++ way is to use a global variable:
volatile unsigned int& UART0 = *((volatile unsigned in... |
2,417,317 | 2,417,499 | Serialization over Pipes | I wrote several simulation programs in C++ and want to connect their outputs/inputs with pipes (best solution would probably be to use the C++ streams).
For this I would like to serialize some objects (for example the simulations output/input are tensors and matrices). How should I handle this problem? I searched aroun... | Check these libraries:
http://en.wikipedia.org/wiki/Thrift_(protocol)
http://code.google.com/apis/protocolbuffers/
|
2,417,484 | 2,417,527 | Winsock only sending data at program close | I have a c++/windows program that receives data from another c++ program via a WM_COPYDATA message. It is then supposed to use Sockets/winsock to send this message on to a server written in Java. The client connects to the server fine, but it doesn't seem to be able to send messages in a timely fashion. However, once t... | You are reading lines on the server, but you are not sending lines.
That means your server sits there, receiving data but waiting to return a line of text back to your program from readLine() , which does not happen since no newlines , \n, gets sent. When the client exits, readLine() gives you back the data it read th... |
2,417,494 | 2,417,555 | Passing a string variable as a ref between a c# dll and c++ dll | I have a c# dll and a c++ dll . I need to pass a string variable as reference from c# to c++ . My c++ dll will fill the variable with data and I will be using it in C# how can I do this. I tried using ref. But my c# dll throwed exception . "Attempted to read or write protected memory. ... This is often an indication th... | As a general rule you use StringBuilder for reference or return values and string for strings you don't want/need to change in the DLL.
StringBuilder corresponds to LPTSTR and string corresponds to LPCTSTR
C# function import:
[DllImport("MyDll.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static void GetMy... |
2,417,583 | 2,417,628 | How to perform Cross-Platform Asynchronous File I/O in C++ | I am writing an application needs to use large audio multi-samples, usually around 50 mb in size. One file contains approximately 80 individual short sound recordings, which can get played back by my application at any time. For this reason all the audio data gets loaded into memory for quick access.
However, when load... | boost has an asio library, which I've not used before (it's not on NASA's list of approved third-party libraries).
My own approach has been to write the file reading code twice, once for Windows, once for the POSIX aio API, and then just pick the right one to link with.
For Windows, use OVERLAPPED (you have to enable i... |
2,417,588 | 2,417,770 | Escaping a C++ string | What's the easiest way to convert a C++ std::string to another std::string, which has all the unprintable characters escaped?
For example, for the string of two characters [0x61,0x01], the result string might be "a\x01" or "a%01".
| Take a look at the Boost's String Algorithm Library. You can use its is_print classifier (together with its operator! overload) to pick out nonprintable characters, and its find_format() functions can replace those with whatever formatting you wish.
#include <iostream>
#include <boost/format.hpp>
#include <boost/algor... |
2,417,608 | 2,417,637 | is c++ STL algorithms and containers same across platforms and performance? | After learning good amount of c++, i'm now into STL containers and algorithms template library, my major concerns are,
1) Is this library same across different platforms like MS, linux n other os?
2) will quality or efficiency of program c++ module decrease with more use of STL containers and algorithms, i think i can'... |
1) Is this library same across different platforms like MS, linux n other os?
No. Except the standardized interface, the implementations are all different for each compiler suite, and sometimes they also provide custom extensions such as hash_map.
2) will quality or efficiency of program c++ module decrease with mor... |
2,417,614 | 2,417,729 | end of istream not detected when expected | I wrote a function to count vowels. If there is a vowel at the end of the stream it gets counted twice. Why?
#include <iostream>
#include <string>
#include <map>
using namespace std;
void countChars(istream& in, string theChars, ostream& out) {
map<char, int> charMap;
map<char, int>::iterator mapIt;
for (string... | Because in evaluates as false when the last read failed due to running out of data, not because the next read would fail due to running out of data. It doesn't "look ahead", it only knows that the stream is finished if it has previously tried and failed to read.
So the following happens:
last char is read and processe... |
2,417,697 | 2,419,231 | gluPerspective was removed in OpenGL 3.1, any replacements? | I'm trying to read some OpenGL tutorials on the net. the problem is that I found some old ones that use gluPerspective(). gluPerspective was deprecated in OpenGL 3.0 and removed in 3.1.
What function can I use instead?
I'm using C++ with latest FreeGlut installed.
| You have to compute the matrix manually and then pass it to OpenGL.
Computing the matrix
This snippet of code is based on the gluPerspective documentation.
void BuildPerspProjMat(float *m, float fov, float aspect,
float znear, float zfar)
{
float f = 1/tan(fov * PI_OVER_360);
m[0] = f/aspect;
m[1] = 0;
m[... |
2,417,859 | 2,417,997 | Template mutual dependence | template
struct A{
typedef float atype;
typedef typename tB::btype typeB;
};
template
struct B{
typedef float btype;
typedef typename tA::atype typeA;
};
struct MyB;
struct MyA: public A<MyB>{};
struct MyB: public B<MyA>{};
int main(int argc, char *argv[])
{
}
does not co... | This cannot be resolved directly. There was a very similar question (although not involving templates) posted yesterday: C++: How can I avoid "invalid covariant return type" in inherited classes without casting?
Your two options are to redesign your solutions so that this cross-dependency is no longer required, or to r... |
2,418,157 | 2,418,175 | C++ error: undefined reference to 'clock_gettime' and 'clock_settime' | I am pretty new to Ubuntu, but I can't seem to get this to work. It works fine on my school computers and I don't know what I am not doing. I have checked usr/include and time.h is there just fine. Here is the code:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
timespec time1, time2;
... | Add -lrt to the end of g++ command line. This links in the librt.so "Real Time" shared library.
|
2,418,170 | 2,418,748 | 'long long int' is interpreted as 'long int'. How do I get round this? | I'm working on project involving c programming for my mathematics course at university.
I need to be able to handle large integers, larger than those that can be stored in a 'long int' datatype. So I tried using 'long long int', but if I try something like this:
long long int number;
number = 10000000000;
Then the er... | In Microsoft environment use printf with this syntax :
__int64 i64 = 10000000000;
unsigned __int64 u64 = 10000000000000000000;
printf ( "%I64d\n", i64 );
printf ( "%I64u\n", u64 );
printf ( "%I64d\n", u64 ); <-- note this typo
|
2,418,244 | 2,418,459 | Basic polynomial reading using linked lists | Ok, after failing to read a polynomial, I'm trying first a basic approach to this.
So i have class polinom with function read and print:
#ifndef _polinom_h
#define _polinom_h
#include <iostream>
#include <list>
#include <cstdlib>
#include <conio.h>
using namespace std;
class polinom
{
class term
{
publi... | if (i == poly.end()) { // if we reached the last term
This comment shows your error. For any given collection of items, items.end() returns the entry after the last item.
For instance, say I have a 5-item std::vector:
[0] [1] [2] [3] [4]
Then begin() points to:
[0] [1] [2] [3] [4]
/\
And end() points to:
[0] [1]... |
2,418,588 | 2,418,742 | Trying to switch a texture when player dies (OpenGL + C++) | I'm creating a 2D game and when the player dies I want the texture I to switch to another (to show an explosion) I also want the game to pause for a second or two so the user can see that the texture has changed.
My textures are loading correctly because I can apply it to a shape and i can see it if I say switched it w... | You need to swap your buffers before you Sleep() if you want to see anything.
More generally, replace the Sleep() with a ExplodeStart, which you set to CurrentTimeInMilliseconds(). Then each time through your render loop check if CurrentTimeInMilliseconds()-ExplodeStart > 1000. If it is, switch to your regular player... |
2,418,739 | 2,424,619 | Empty Win32 Popup Menu | I'm trying to create a dynamic popup menu within my application, the generation code I use is something like that :
HMENU menu;
POINT pt;
menu = CreatePopupMenu();
SetForegroundWindow( receivingWindow );
GetCursorPos( &pt );
int i = 19;
AppendMenu( menu, MF_STRING, i++, _TEXT("meh meh"... | I found a workaround for this problem. Instead of using my main window (receivingWindow), I'm using a message only window to receive the event. For a reason that I don't understand, the text is displayed normally this way.
|
2,418,776 | 2,419,006 | CreateDIBSection leaving 'Not enough storage' error, but seems to still work anyway | Whenever my app tries to create a DIB section, either by calling CreateDIBSection(), or by calling LoadImage() with the LR_CREATEDIBSECTION flag, it seems to return successfully. The HBITMAP it returns is valid, and I can manipulate and display it just fine.
However, calls to GetLastError() will return 8: Not enough s... | I think you aren't following what the documentation says (from CreateDIBSection):
If the function succeeds, the return
value is a handle to the newly created
DIB, and *ppvBits points to the bitmap
bit values.
If the function fails, the return
value is NULL, and *ppvBits is NULL.
This function can return the ... |
2,418,777 | 2,714,580 | Compiling boost on Sunos | I have just started with using boost libraries.
For one of our projects i want to compile Boost 1.39.0 on Sun OS using sun compiler. However if i compile it using steps mentioned in http://www.boost.org/doc/libs/1_39_0/more/getting_started/unix-variants.html, not all of the targets are compiled. Can someone provide res... | The SunOS compiler is notorious for not having conformant libraries and compilation. But we do have at least one tester that uses the platform (see Sandia-sun tester). And from what you can see there are many failures in the toolset. As for setting it up the key thing to do is not use the standard STD lib, but use the ... |
2,418,841 | 2,418,908 | Differences among including <xstring>, <cstring>, <string> and <wstring> in C++ | I have seen the following #include directives:
#include <xstring>
#include <cstring>
#include <string>
#include <wstring>
What are the differences among these include directives? Did I miss any others that should be considered part of this group?
| <string> is where std::string is defined.
<xstring> is a Microsoft C++ header containing the actual implementation of the std::basic_string template. You never need to include <xstring> yourself. <string> includes it for the basic_string implementation.
<cstring> is the standard C string library (strcpy, strcat, etc) p... |
2,418,921 | 2,418,951 | How do I get CPU Clock Speed in C++ (Linux)? | How can I get the CPU clock speed in C++?
I am running Ubuntu 9.10 if that makes any difference.
| Read the pseudo-file /proc/cpuinfo. See this link for an explanation of the fields it contains.
|
2,419,068 | 2,419,814 | How to debug a segmentation fault while the gdb stack trace is full of '??'? | My executable contains symbol table. But it seems that the stack trace is overwrited.
How to get more information out of that core please? For instance, is there a way to inspect the heap ? See the objects instances populating the heap to get some clues. Whatever, any idea is appreciated.
| I am a C++ programmer for a living and I have encountered this issue more times than i like to admit. Your application is smashing HUGE part of the stack. Chances are the function that is corrupting the stack is also crashing on return. The reason why is because the return address has been overwritten, and this is ... |
2,419,107 | 2,419,136 | Replacing special characters from HTML source | I'm new to HTML coding and I know HTML has some reserved characters for its use and it also displays some characters by their character code. For example -:
Œ is Œ
© is ©
® is ®
I have the HTML source in std::string. how can i decipher them into their actual form and replace from std::string? i... | I would recommend using some HTML/XML parser that can automatically do the conversion for you. Parsing HTML correctly by hand is extremely difficult. If you insist on doing it yourself, Boost String Algorithms library provides useful replacement functions.
|
2,419,137 | 2,419,161 | Is filling memory with non zero values slower than filling it with zeros? | I'm not very expert on how processors work, but one might imagine that it was easier to set chunks of memory to zero than non zero values and so it may be marginally faster.
| I think the only difference would be in setting up the register that has the value to store to memory. Some processors have a register that's fixed at zero (ia64 for example). Even so, whatever minuscule overhead there might be for setting up a register will be monstrously dwarfed by the writing to memory.
As far as ... |
2,419,562 | 2,419,597 | Convert seconds to Days, Minutes and Seconds | Hey everyone. I've continuing to learn C++ and I've been set the 'challenge' of converting seconds to format as the Days,Minutes and Seconds.
For example: 31600000 = 365 days, 46 minutes, 40 seconds.
using namespace std;
const int hours_in_day = 24;
const int mins_in_hour = 60;
const int secs_to_min = 60;
long input_s... | One of the things about programming is that there is never just one way to do something. In fact if I were to set my mind to it, I might be able to come up with a dozen completely different ways to accomplish this. You're not missing anything if your code meets requirements.
For your amusement, here's a way to format... |
2,419,601 | 2,419,835 | Vim, C++, look up member function | I am using vim 7.x
I am using alternate file.
I have a mapping of *.hpp <--> *.cpp
Suppose I'm in
class Foo {
void some_me#mber_func(); // # = my cursor
}
in Foo.hpp
is there a way to tell vim to do the following:
Grab word under # (easy, expand("")
Look up the class I'm inside of ("Foo") <-- I have no idea how t... | This is relatively easy to do crudely and very difficult to do well. C and C++ are rather complex languages to parse reliably. At the risk of being downvoted, I'd personally recommend parsing the tags file generated by ctags, but if you really want to do it in Vim, there are a few of options for the "crude" method.
... |
2,419,650 | 2,419,720 | C/C++ macro/template blackmagic to generate unique name | Macros are fine.
Templates are fine.
Pretty much whatever it works is fine.
The example is OpenGL; but the technique is C++ specific and relies on no knowledge of OpenGL.
Precise problem:
I want an expression E; where I do not have to specify a unique name; such that a constructor is called where E is defined, and a de... | If your compiler supports __COUNTER__ (it probably does), you could try:
// boiler-plate
#define CONCATENATE_DETAIL(x, y) x##y
#define CONCATENATE(x, y) CONCATENATE_DETAIL(x, y)
#define MAKE_UNIQUE(x) CONCATENATE(x, __COUNTER__)
// per-transform type
#define GL_TRANSLATE_DETAIL(n, x, y, z) GlTranslate n(x, y, z)
#defi... |
2,419,805 | 2,419,830 | When did "and" become an operator in C++ | I have some code that looks like:
static const std::string and(" AND ");
This causes an error in g++ like so:
Row.cpp:140: error: expected unqualified-id before '&&' token
so after cursing the fool that defined "and" as &&, I added
#ifdef and
#undef and
#endif
and now I get
Row.cpp:9:8: error: "and" cannot be used ... | There are several such alternatives defined in C++. You can probably use switches to turn these on/off.
|
2,419,857 | 2,420,060 | Java or C++ for my particular agent-based model (ABM)? | I unfortunately need to develop an agent-based model. My background is C++; I'm decent but not a professional programmer. My goal is to determine whether, my background aside for the moment, the following kind of algorithm would be faster or dramatically easier to write in C++ or Java.
My agents will be of class Host. ... | I'm under the impression that Java will delete all these pointers implicitly if I delete the underlying object. Is this true?
Nope. You actually have it backwards; if you delete all the pointers, Java will delete the underlying object. So you'll still need to search through all three of your data structures (hosts, ... |
2,419,919 | 2,419,970 | A problem with random number generation | I am taking a course on programming, and we're using C++.
We had an assignment where, at some point, we needed to code a function that would return a random number in an [upper, lower] interval. I used the following:
lower + (int) (upper * (rand() / (RAND_MAX + 1.0)));
I did not forget to change srand by using srand((... | Given that rand() is not a very strong random number generator, the small amount of bias added by the standard approach is probably not an issue: (higher-lower) needs to be smaller than MAX_RAND of course.
lower + rand() % (higher-lower+1);
fixed off by one error.
|
2,419,928 | 2,496,979 | Where to get pure C++ Lame MP3 encoder - PCM to MP3 example? | So all I need is a simple function that sets it up (eating incoming PCM RATE (for example: rate near to 44100) It's channels (for example: 2) and -bits (for example: 16) and desirable 128 kb\s rate) and another one that takes PCM data and encodes it into pure MP3 frames.
I know it looks like a silly homework task but I... | See the example I gave in your other question for the basic usage of Lame. It should contain everything you need.
|
2,420,043 | 2,420,097 | memmove, memcpy, and new | I am making a simple byte buffer that stores its data in a char array acquired with new and I was just wondering if the memcpy and memmove functions would give me anything weird if used on memory acquired with new or is there anything you would recommend doing instead?
| No, they are perfectly fine. new and malloc() are just two different ways in you can aquire memory on the heap (actually they are quite the same, because new uses malloc() under the hood in most implementations). As soon as you have a valid char* variable in your hand (allocated by new, malloc() or on the stack) it is ... |
2,420,131 | 2,422,014 | Detect insertion of media into a drive using windows messages | I am currently using WM_DEVICECHANGE to be notified when new USB drives are connected to the computer. This works great for devices like thumb-drives where as soon as the device arrives it is ready to have files read from it. For devices like SD card readers it does not because the message is sent out once when the d... | I just did this a few weeks ago. Technically speaking the RegisterDeviceNotification route is the proper way to go, but it requires a decent amount of work to get right. However, Windows Explorer already does all of the hard work for you. Just use SHChangeNotifyRegister with SHCNE_DRIVEADD / SHCNE_DRIVEREMOVED / SHC... |
2,420,346 | 2,420,382 | C API function callbacks into C++ member function code | So, I'm using the FMOD api and it really is a C api.
Not that that's bad or anything. Its just it doesn't interface well with C++ code.
For example, using
FMOD_Channel_SetCallback( channel, callbackFunc ) ;
It wants a C-style function for callbackFunc, but I want to pass it a member function of a class.
I ended up u... | You cannot directly pass a member function. A member function has the implicit parameter this and C functions don't.
You'll need to create a trampoline (not sure the signature of the callback, so just doing something random here).
extern "C" int fmod_callback( ... args ...)
{
return object->member();
}
One issue ... |
2,420,380 | 2,420,432 | XML Parsing: Checking for strings within string C++ | I have written a simple C++ shell program to parse large XML files and fix syntax errors.
I have so far covered everything I can think of except strings within strings, for example.
<ROOT>
<NODE attribute="This is a "string within" a string" />
<ROOT>
My program loops through the entire xml file character by charact... | I think it's difficult to decide where the attribute ends and another begins. I think you need to restrict the possible input you can parse otherwise you will have ambiguous cases such as this one:
<ROOT>
<NODE attribute="This is a "string within" a string" attribute2="This is another "string within" a string" />
<RO... |
2,420,484 | 4,666,302 | How can I make gcc understand this template syntax? | I'm trying to use a delegate library in gcc http://www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx but the "preferred syntax" is not recognized by gcc 4.3. I.e. howto make compiler understand the
template < RET_TYPE (ARG1, ARG2) > syntax instead of template ??
TIA
/Rob
| If a class has a template function as:
class A {
public:
template<typename T>
static void doThis() {...}
};
template<typename T>
class B {
public:
static void doThat() {
A::doThis<T>();
}
};
then VC++ recognizes the syntax in class B, but for GCC you have to insert keyword template:
template<ty... |
2,420,496 | 2,437,785 | Drop target - where do I register the COleDropTarget variable if the view class doesn't have OnCreate? | The MSDN site says:
From your view class's function that handles the WM_CREATE message (typically OnCreate), call the new member variable's Register member function. Revoke will be called automatically for you when your view is destroyed.
But I don't have an OnCreate function in the ChildView class.
I do have OnCreat... | Solved:
In using F1 to get the syntax for OnDrop and the others, MSDN gave me:
virtual BOOL OnDrop(
CWnd* pWnd,
COleDataObject* pDataObject,
DROPEFFECT dropEffect,
CPoint point
);
But the correct virtual function does not have the first parameter and should be:
virtual BOOL OnDrop(
COleDataObject* pDat... |
2,420,506 | 2,420,687 | Finding cells in a grid with varying grid cell sizes | I have a grid of rectangular cells covering a plane sitting at some distance from the coordinate system origin and would like to identify the grid cell where a straight line starting at the origin would intersect it.
The cells on the grid have equal sizes (dx,dy) and there are no gaps between cells, but since every cel... |
[...]but I am more interested in what algorithms there are that do nearest-neighbor searches on regularly spaced inputs.
Though they are data structures to be very specific, I think you should take a look at the following:
R Tree
BK Tree
|
2,420,663 | 2,422,653 | windows equivalent of inet_aton | I'm converting some code written for a linux system to a windows system. I'm using C++ for my windows system and wanted to know the equivalent of the function inet_aton.
| Windows supports inet_pton, which has a similar interface to inet_aton (but that works with IPV6 addresses too). Just supply AF_INET as the first parameter, and it will otherwise work like inet_aton.
(If you can change the Linux source, inet_pton will also work there).
|
2,420,777 | 2,420,822 | Is there a way to use thread local variables when using ACE? | I am using ACE threads and need each thread to have its own int member.
Is that possible?
| ACE calls this "Thread Specific Storage". Check this out: ACE_TSS. That's about all I know about it, sorry can't be more help.
The Wikipedia page for thread-local storage says there is a pthreads way to do this too.
|
2,421,197 | 2,421,215 | How do acquire a xml string for a child using msxml4? | Using MSXML4, I am creating and saving an xml file:
MSXML2::IXMLDOMDocument2Ptr m_pXmlDoc;
//add some elements with data
SaveToDisk(static_cast<std::string>(m_pXmlDoc->xml));
I now need to acquire a substring from m_pXmlDoc->xml and save it. For example, if the full xml is:
<data>
<child1>
<A>data</A>
... | Use XPath queries. See the MSDN documentaion for querying nodes. Basically you need to call the selectNodes API with the appropriate XPath expression that matches the part of the DOM you are interested in.
// Query a node-set.
MSXML4::IXMLDOMNodeListPtr pnl = pXMLDom->selectNodes(L"//child/*");
|
2,421,219 | 2,421,250 | Best C++ static & run time tools | Apologies if I missed this question already, but I searched and couldn't find it.
I have been out the C/C++ world for a little while and am back on a project. I was wondering what tools are preferred today to help with development.
The types of tools I'm referring to are:
Purify
Electric Fence
PC-Lint
cscope
Thanks!... | You already have mentioned some of the (mostly free) alternatives. This depends on the platform again.
Windows:
VSTS 2008 is pretty good with its /analyze and profiling tools
Rational Purify (as you've mentioned)
BoundsChecker
Linux:
Valgrind
Mac:
Shark
CHUD
Sleuth
MalloDebug
|
2,421,254 | 2,421,438 | Static and global variable in memory |
Are static variables stored on the stack itself similar to globals? If so, how are they protected to allow for only local class access?
In a multi threaded context, is the fear that this memory can be directly accessed by other threads/ kernel? or why cant we use static/global in multi process/ thread enviornment?
| Variables stored on the stack are temporal in nature. They belong to a function, etc and when the function returns and the corresponding stack frame is popped off, the stack variables disappear with it. Since globals are designed to be accessible everywhere, they must not go out of context and thus are stored on the ... |
2,421,485 | 2,421,651 | Could not send backspace key using ::SendInput() to wordpad application | I have used sendinput() function and windows keyboard hooks to develop a custom keyboard for indian languages.
Project is in google code here: http://code.google.com/p/ekalappai
The keyboad hook and sendinput functions are placed in a win32 dll. And they are called from a Qt exe.
Our application works fine for most ke... | You are mixing up the virtual key and the scan code. The wVk member is the important one, the scan code will only be used it the virtual key is ambiguous. Fix:
kb.wVk = vk;
kb.wScan = 0; // TODO: look at VkKeyScanEx()
|
2,421,492 | 2,421,671 | Visibility of privately inherited typedefs to nested classes | In the following example (apologies for the length) I have tried to isolate some unexpected behaviour I've encountered when using nested classes within a class that privately inherits from another. I've often seen statements to the effect that there is nothing special about a nested class compared to an unnested class,... | Preface: In the answer below I refer to some differences between C++98 and C++03. However, it turns out that the change I'm talking about haven't made it into the standard yet, so C++03 is not really different from C++98 in that respect (thanks to Johannes for pointing that out). Somehow I was sure I saw it in C++03, b... |
2,421,771 | 2,421,781 | What is the Win compile switch to turn off #pragma deprecated warning? | Using Visual Studio .NET 2003 C++ and the wininet.dll
Am seeing many C4995 warnings
More info
Any help is appreciated.
Thanks.
| You can use #pragma warning as shown on that MSDN page:
#pragma warning(disable: 4995)
Or, you can turn the warning off for the whole project in the project's properties (right click project -> Properties -> C/C++ -> Advanced -> Disable Specific Warnings). On the command line, you can achieve the same effect using /w... |
2,421,783 | 2,421,831 | Queue giving erroneous data | So I'm attempting to use a queue to parse some input, turning prefix mathematical expressions into infix mathematical expressions with parentheses. For example: +++12 20 3 4 turns into (((12+20)+3)+4). For the most part, my algorithm works, except for one specific thing. When the numbers are greater than 2 digits long,... | While I don't have the exact answer to your problem, I did notice this:
std::string *s = new std::string();
getNum( s, str, beg, len );
//std::cout << s->c_str() << std::endl;
n->push( const_cast< char* >( s->c_str() ) );
delete s;
The problem there is you are pushing s into the queue and then you are deleting it. The... |
2,421,833 | 2,422,076 | Qt - How to do superscripts and subscripts in a QLineEdit? | I need to have the ability to use superscripts asnd subscripts in a QLineEdit in Qt 4.6. I know how to do superscripts and subscripts in a QTextEdit as seen below but I can't figure out how to do them in QLineEdit because the class doesn't contain a mergeCurrentCharFormat() function like QTextEdit does. Please help. Th... | QLineEdit wasn't really made for this type of thing, as it was designed for simple text entry. You have a few options, however. The simplest one is to do as Hostile Fork suggested and use a QTextEdit, and add a style override to not show the scroll bar (which I assume would remove the arrows). The more complex one w... |
2,422,068 | 2,422,080 | How can I run an external program without waiting for it to exit? | I'm trying to execute an external program from inside my Linux C++ program.
I'm calling the method system("gedit") to launch an instance of the Gedit editor. However my problem is while the Gedit window is open, my C++ program waits for it to exit.
How can I call an external program without waiting for it to exit?
| You will need to use fork and exec
int fork_rv = fork();
if (fork_rv == 0)
{
// we're in the child
execl("/path/to/gedit", "gedit", 0);
// in case execl fails
_exit(1);
}
else if (fork_rv == -1)
{
// error could not fork
}
You will also need to reap your child so as not to leave a zombie process. ... |
2,422,155 | 2,535,751 | how to get namespace prefixes from XML document, using MSXML? | For example,
In this document
< ?xml version="1.0" ? >
< SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ns1="ht... | If you're doing XML processing you shouldn't need to know the prefix.
To select a node in an XML document, you need not know the prefix. You need to know the namespace, not the prefix.
If you are processing a SOAP document, then you know the namespace is http://schemas.xmlsoap.org/soap/envelope/. And that's all y... |
2,422,273 | 2,422,279 | One question about vector push_back | I just noticed that for vector push_back it is push back a reference to the element.
void push_back ( const T& x );
My question is does the memory layout changed after push_back?
For example, I have an array first which containing five elements and the layout is like this.
| | | | ... | A vector stores by value not by reference.
When you re-add the same element, a copy will be stored at the end. If you do not want to make a copy of the values you are inserting into the vector, then you should use pointers instead.
Example:
std::vector<std::string> v;
string s = "";
v.push_back(s);
s = "hi";
v.push_... |
2,422,419 | 2,422,444 | Disable full keyboard and mouse when console of c is running in window OS | Is it possible to disable full keyboard and mouse when I run my c program in window OS. Kindly guide me how can I make it possible.
| What about BlockInput()?
|
2,422,430 | 2,424,210 | Hide the console of a C program in the Windows OS | I want to hide my console of C when I run my application. How can I make my application run in the background?
| Programs with main() by default are compiled as SUBSYSTEM:CONSOLE applications and get a console window. If you own the other processes your application is starting, you could modify them to be windowed applications by one of the following methods:
Modify them to use WinMain() instead of main(). This is the typical ... |
2,422,431 | 2,422,457 | Is a "factory" method the right pattern? | So I'm working to improve an existing implementation. I have a number of polymorphic classes that are all composed into a higher level container class. The problem I'm dealing with at the moment is that the higher level container class, well, sucks. It looks something like this, which I really don't have a problem with... | Dependency injection springs to mind.
|
2,422,588 | 2,424,136 | How to add existing project using environment variable? | I have a a project that resides on a "thumb drive" (a.k.a. memory stick). Due to Windows ability to change drive letters of thumb drives, I would like to specify the location of sub-projects using an environment variable. This allows me to set the thumb drive drive letter, depending on the PC that I am using; or chan... | The best solution here is to use relative paths for your subprojects. The relative path from your solution file to the subprojects does not change, as both are on the same thumb drive.
|
2,422,625 | 2,422,637 | Using clang to analyze C++ code | We want to do some fairly simple analysis of user's C++ code and then use that information to instrument their code (basically regen their code with a bit of instrumentation code) so that the user can run a dynamic analysis of their code and get stats on things like ranges of values of certain numeric types.
clang shou... | clang is designed to be modular. Quoting from its page:
A major design concept for clang is
its use of a library-based
architecture. In this design, various
parts of the front-end can be cleanly
divided into separate libraries which
can then be mixed up for different
needs and uses.
Look at clang librarie... |
2,422,704 | 2,423,530 | Unit Testing Refcounted Critical Section Class | I'm looking at a simple class I have to manage critical sections and locks, and I'd like to cover this with test cases. Does this make sense, and how would one go about doing it? It's difficult because the only way to verify the class works is to setup very complicated threading scenarios, and even then there's not a g... | Here are three options and personally I favour the last one...
You could create a 'critical section factory' interface that can be passed to your constructor. This would have functions that wrapped the API level functions that you need to use. You could then mock this interface up and pass the mock to the code when un... |
2,422,755 | 2,423,930 | How can I force Doxygen to show full include path? | How can I force Doxygen to show full include path?
What do I mean:
I have a class foo::bar::bee defined in bee.hpp in following directory structure:
foo
foo/bar
foo/bar/bee.hpp
Doxygen, when it documents foo::bar::bee class tells that you need to include <bee.hpp>, but for my software I need <foo/bar/bee.hpp>
How can ... | Taken directly from the hints in DoxyWizard:
STRIP_FROM_INC_PATH
The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the path mentioned in the documentation of a class, which tells the reader which header file to include in order to use a class. If left blank only the name of the header file contai... |
2,422,843 | 2,422,992 | Writing preprocessor directives to get string | Can you write preprocessor directives to return you a std::string or char*?
For example: In case of integers:
#define square(x) (x*x)
int main()
{
int x = square(5);
}
I'm looking to do the same but with strings like a switch-case pattern. if pass 1 it should return "One" and 2 for "Two" so on..
| You don't want to do this with macros in C++; a function is fine:
char const* num_name(int n, char const* default_=0) {
// you could change the default_ to something else if desired
static char const* names[] = {"Zero", "One", "Two", "..."};
if (0 <= n && n < (sizeof names / sizeof *names)) {
return names[n]... |
2,422,881 | 2,437,771 | Why is OnDragEnter not called? | I have added the COleDropTarget variable to my view class and registered it in the OnCreate(), which is being called at startup. I added the OnDragEnter and OnDrop virtual functions (not the others yet, as OnDragLeave). But they are not called when I drag (or drop) a piece of text over them.
I just happened to think ab... | Solved:
In using F1 to get the syntax for OnDrop and the others, MSDN gave me:
virtual BOOL OnDrop(
CWnd* pWnd,
COleDataObject* pDataObject,
DROPEFFECT dropEffect,
CPoint point
);
But the correct virtual function does not have the first parameter and should be:
virtual BOOL OnDrop(
COleDataObject* pDat... |
2,422,889 | 2,423,161 | How do you correctly use boost::make_shared_ptr? | This simple example fails to compile in VS2K8:
io_service io2;
shared_ptr<asio::deadline_timer> dt(make_shared<asio::deadline_timer>(io2, posix_time::seconds(20)));
As does this one:
shared_ptr<asio::deadline_timer> dt = make_shared<asio::deadline_timer>(io2);
The error is:
error C2664: 'boost::asio::basic_d... | The problem is that asio::deadline_timer has a constructor that requires a non-const reference to a service. However, when you use make_shared its parameter is const. That is, this part of make_shared is the problem:
template< class T, class A1 > // service is passed by const-reference
boost::shared_ptr< T > make_share... |
2,422,898 | 2,423,229 | Intel MKL memory management and exceptions | I am trying out Intel MKL and it appears that they have their own memory management (C-style).
They suggest using their MKL_malloc/MKL_free pairs for vectors and matrices and I do not know what is a good way to handle it. One of the reasons for that is that memory-alignment is recommended to be at least 16-byte and wit... | You could use a std::vector with a custom allocator like the ones mentioned here to ensure 16 byte alignment. Then you can just take address of the first element as the input pointer to the MKL functions. It is important that you have 16 byte alignment since the MKL uses SIMD extensively for performance.
|
2,422,970 | 2,423,091 | C++ class object memory map | When we create an object of a class what does it memory map look like. I am more interested in how the object calls the non virtual member functions. Does the compiler create a table like vtable which is shared between all objects?
class A
{
public:
void f0() {}
int int_in_b1;
};
A * a = new A;
What will be the m... | You can imagine this code:
struct A {
void f() {}
int int_in_b1;
};
int main() {
A a;
a.f();
return 0;
}
Being transformed into something like:
struct A {
int int_in_b1;
};
void A__f(A* const this) {}
int main() {
A a;
A__f(&a);
return 0;
}
Calling f is straight-forward because it's non-virtual. ... |
2,423,052 | 2,423,322 | Problem related to dll | Can anyone guide me what could be the problem in the mentioned below:-
alt text http://lh5.ggpht.com/_D1MfgvBDtsU/S5iLmYivj1I/AAAAAAAAABU/8Mquam_XxZ4/s912/dll%20issue.PNG
This PP folder is present in the following path at my desk "E:\WINCE600\PLATFORM\COMMON\SRC\SOC\COMMON_FSL_V2_PDK1_7\IPUV3"
In this IPUV3 folder, PP ... | Was everything working as expected before the code change?
Are you getting any build errors?
Do you have a DIRS file in the IPUV3 directory that specifies the two subdirectories?
What is the problem? State what you did, what you expect and what was the outcome. It is not clear right now.
Update:
According to the com... |
2,423,270 | 2,424,390 | Adding an allocator to a C++ class template for shared memory object creation | In short, my question is: If you have class, MyClass<T>, how can you change the class definition to support cases where you have MyClass<T, Alloc>, similar to how, say, STL vector provides.
I need this functionality to support an allocator for shared memory. Specifically, I am trying to implement a ring buffer in shar... | what make me confuse is, why you need to allocate or create an object in SharedMemory (SHM), for example if you reserve shared memory of the size 65536 Bytes, then suppose you get your shared memory at address 0x1ABC0000, if reservation success you will have free and directly accessible memory space at 0x1ABC0000 to 0x... |
2,423,352 | 2,424,358 | what's the deal with compile time evaluation of constant arithmetic, and can it be done in the pre processor? | template <int T>
void aFunc(){}
int main()
{
int anArray[45-32];
switch(4)
{
case 4<45:
break;
}
aFunc<4*3/7&8 == 45 - 5>();
}
so this all compiles in VC++ 2005
is this standard? if so, what do the conditional operators return? 0 and 1? are there limits?
and the thing that interests ... | I think you misunderstand a bit.
The actual evaluation of constant expressions is done by the compiler, not the preprocessor. The preprocessor only evaluates macros, which is about textual substitution.
If you check out Boost.Preprocessor, you'll realize that even simple operations like addition or soustractions cannot... |
2,423,415 | 2,423,431 | C++ - Unwanted characters printed in output file | This is the last part of the program I am working on. I want to output a tabular list of songs to cout. And then I want to output a specially formatted list of song information into fout (which will be used as an input file later on).
Printing to cout works great. The problem is that tons of extra character are added w... | Most likely, one of your methods returns an improper char * string (not null terminated).
Edit: actually, not just one: getPlaylistName(), getSongName() and getArtistName().
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.