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 |
|---|---|---|---|---|
119,999 | 120,234 | How to setup a shared ccache | How can I setup a shared ccache without falling into a permissions problem?
I would like to run a nightly or CI build with latest changes and share all created binaries throughout the R&D using a large ccache repository.
| The easiest solution: create a new group (e.g. "devel"), and make all developers members of it. Give read/write permissions to that group on the directory hierarchy where the cache is maintained. The developers will also need to fix their umask.
|
120,033 | 120,084 | Any workarounds for non-static member array initialization? | In C++, it's not possible to initialize array members in the initialization list, thus member objects should have default constructors and they should be properly initialized in the constructor. Is there any (reasonable) workaround for this apart from not using arrays?
[Anything that can be initialized using only the i... | One possible workaround is to avoid the compiler calling the OtherClass constructor at all, and to call it on your own using placement new to initialize it whichever way you need. Example:
class Foo
{
private:
char inst[3*sizeof(OtherClass)]; // Array size fixed. OtherClass has no default ctor.
// use In... |
120,876 | 120,916 | What are the rules for calling the base class constructor? | What are the C++ rules for calling the base class constructor from a derived class?
For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).
| Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by ... |
120,957 | 121,014 | C++ usage in embedded systems | What features of C++ should be avoided in embedded systems?
Please classify the answer by reason such as:
memory usage
code size
speed
portability
EDIT: Lets' use an ARM7TDMI with 64k ram as a target to control the scope of the answers.
| RTTI and Exception Handling:
Increases code-size
Decreases performance
Can often be replaced by cheaper mechanisms or a better software-design.
Templates:
be careful with them if code-size is an issue. If your target CPU has no or only a very tiny ínstruction cache it may reduce the performance as well. (templates t... |
121,162 | 121,163 | What does the explicit keyword mean? | What does the explicit keyword mean in C++?
| The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.
Here's an example class with a constructor that ... |
121,326 | 121,370 | What does the GDB backtrace message "0x0000000000000000 in ?? ()" mean? | What does it mean when it gives a backtrace with the following output?
#0 0x00000008009c991c in pthread_testcancel () from /lib/libpthread.so.2
#1 0x00000008009b8120 in sigaction () from /lib/libpthread.so.2
#2 0x00000008009c211a in pthread_mutexattr_init () from /lib/libpthread.so.2
#3 0x0000000000000000 in ?? ()
... | gdb wasn't able to extract the proper return address from pthread_mutexattr_init; it got an address of 0. The "??" is the result of looking up address 0 in the symbol table. It cannot find a symbolic name, so it prints a default "??"
Unfortunately right offhand I don't know why it could not extract the correct return a... |
121,757 | 121,805 | How do you implement Coroutines in C++ | I doubt it can be done portably, but are there any solutions out there? I think it could be done by creating an alternate stack and reseting SP,BP, and IP on function entry, and having yield save IP and restore SP+BP. Destructors and exception safety seem tricky but solvable.
Has it been done? Is it impossible?
| Yes it can be done without a problem. All you need is a little assembly code to move the call stack to a newly allocated stack on the heap.
I would look at the boost::coroutine library.
The one thing that you should watch out for is a stack overflow. On most operating systems overflowing the stack will cause a segfaul... |
121,787 | 121,818 | What is the STL implementation with the lowest memory footprint? | I am working on a very large scale computing library that is using STL heavily. The library is being built using MSVC2003 and it is using its STL implementation.
I am looking for an alternative STL implementation that would help the library lower its memory requirements and increase its performance.
It is not possible ... | STLPort. Haven't measured memory usage differences, but it's definitely quicker (yes, real world usage).
|
122,316 | 122,368 | Template Constraints C++ | In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:
interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main(stri... | As someone else has mentioned, C++0x is getting this built into the language. Until then, I'd recommend Bjarne Stroustrup's suggestions for template constraints.
Edit: Boost also has an alternative of its own.
Edit2: Looks like concepts have been removed from C++0x.
|
122,455 | 122,485 | Handling file paths cross platform | Do any C++ GNU standalone classes exist which handle paths cross platform? My applications build on Windows and LInux. Our configuration files refer to another file in a seperate directory. I'd like to be able to read the path for the other configuration file into a class which would work on both Linux or Windows.
W... | Unless you're using absolute paths, there's no need to translate at all - Windows automatically converts forward slashes into backslashes, so if you use relative paths with forward slash path separators, you'll be golden. You should really avoid absolute paths if at all possible.
|
122,782 | 123,233 | How can I wrap BOOST in a separate namespace? | I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines:
boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();
boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
| I read (well scanned) through the development list discussion. There's no easy solution. To sum up:
Wrapping header files in a namespace declaration
namespace boost_1_36_0 {
#include <boost_1_36_0/boost/regex.hpp>
}
namespace boost_1_35_0 {
#include <boost_1_35_0/boost/shared_ptr.hpp>
}
Requires modifyin... |
122,886 | 122,937 | Fast plane rotation algorithm? | I am working on an application that detects the most prominent rectangle in an image, then seeks to rotate it so that the bottom left of the rectangle rests at the origin, similar to how IUPR's OSCAR system works. However, once the most prominent rectangle is detected, I am unsure how to take into account the depth co... | You don't actually need to deal with the 3D information in this case, it's just a mappping function, from one set of coordinates to another.
Look at affine transformations, they're capable of correcting simple skew and perspective effects. You should be able to find code somewhere that will calculate a transform from t... |
123,012 | 123,063 | Do you use Qt and why do you use it? | Pros. and cons? how long do you use it? What about jambi?
| I've used Qt on a couple of projects I did in c++ on several platforms over a period of seven years. I think it works pretty well and definitely was quicker for me to develop a decent GUI app on the Mac than plodding through a language I didn't know (Objective-C) at the time.
I think the signal/slot mechanism is a bit... |
123,758 | 123,765 | How do I remove code duplication between similar const and non-const member functions? | Let's say I have the following class X where I want to return access to an internal member:
class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determin... | Yes, it is possible to avoid the code duplication. You need to use the const member function to have the logic and have the non-const member function call the const member function and re-cast the return value to a non-const reference (or pointer if the functions returns a pointer):
class X
{
std::vector<Z> vecZ;
... |
124,623 | 124,676 | Computing pseudo-inverse of a matrix in C++ | I'm looking to compute the Moore-Penrose pseudo-inverse of a matrix in C++, can someone point me to a library implementation or a numerical recipe?
Thanks!
| You need 'Single Value Decomposition', from which you can find a C implementation here from Numerical Recipes in C.
This other site describes how to use single value decomposition to calculate the pseudo-inverse.
|
124,880 | 124,904 | Is it possible to prevent stack allocation of an object and only allow it to be instantiated with 'new'? | Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?
| One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:
class Foo
{
public:
~Foo();
static Foo* createFoo()
{
return new Foo();
}
private:
Foo();
Foo(const Foo&);
Foo& operator=(const... |
124,966 | 124,970 | Existence map in C++ | I want something like an std::map, but I only want to see if the item exists or not, I don't actually need a key AND a value. What should I use?
| Looks like you need a std::set.
|
125,094 | 125,454 | Transparently swapping pointers to character arrays in C++ | I have a 2D character array:
char nm[MAX1][MAX2] = { "john", "bob", "david" };
I want to swap two of these elements (without std::swap) by simply writing
swapPointers(nm[0], nm[1]);
where swapPointers looks like this
void swapPointers(char *&a, char *&b)
{
char *temp = a;
a = b;
b = a;
}
Howeve... | Zan is close, but his problem is that his 'swap' function can take any pointer to characters. This can cause problems if misused. Here is a safer version:
void swap(char (&x)[MAX2], char (&y)[MAX2])
{
char temp[MAX2];
memcpy(temp, x, MAX2);
memcpy(x, y, MAX2);
memcpy(y, temp, MAX2);
}
There is also ... |
125,124 | 125,225 | C++ Passing Options To Executable | How do you pass options to an executable? Is there an easier way than making the options boolean arguments?
EDIT: The last two answers have suggested using arguments. I know I can code a workable solution like that, but I'd rather have them be options.
EDIT2: Per requests for clarification, I'll use this simple exam... | You seem to think that there is some fundamental difference between "options" that start with "--" and "arguments" that don't. The only difference is in how you parse them.
It might be worth your time to look at GNU's getopt()/getopt_long() option parser. It supports passing arguments with options such as --number-of-l... |
125,580 | 125,605 | What are the advantages of using the C++ Boost libraries? | So, I've been reading through and it appears that the Boost libraries get used a lot in practice (not at my shop, though). Why is this? and what makes it so wonderful?
| Boost is used so extensively because:
It is open-source and peer-reviewed.
It provides a wide range of platform agnostic functionality that STL missed.
It is a complement to STL rather than a replacement.
Many of Boost developers are on the C++ standard committee. In fact, many parts of Boost is considered to be inc... |
125,597 | 125,811 | Boost dependency for a C++ open source project? | Boost is meant to be the standard non-standard C++ library that every C++ user can use. Is it reasonable to assume it's available for an open source C++ project, or is it a large dependency too far?
| Basically your question boils down to “is it reasonable to have [free library xyz] as a dependency for a C++ open source project.”
Now consider the following quote from Stroustrup and the answer is really a no-brainer:
Without a good library, most interesting tasks are hard to do in
C++; but given a good library, a... |
125,806 | 128,327 | Capturing Input in Linux | First, yes I know about this question, but I'm looking for a bit more information that that. I have actually, a fairly similar problem, in that I need to be able to capture input for mouse/keyboard/joystick, and I'd also like to avoid SDL if at all possible. I was more or less wondering if anyone knows where I can get ... | Using the link below look at the function void kGUISystemX::Loop(void)
This is my main loop for getting input via keyboard and mouse using X Windows on Linux.
http://code.google.com/p/kgui/source/browse/trunk/kguilinux.cpp
Here is a snippet:
if(XPending(m_display))
{
XNextEvent(m_display, &m_e);
... |
125,880 | 125,899 | Can anyone recommend a C++ std::map replacement container? | Maps are great to get things done easily, but they are memory hogs and suffer from caching issues. And when you have a map in a critical loop that can be bad.
So I was wondering if anyone can recommend another container that has the same API but uses lets say a vector or hash implementation instead of a tree implementa... | See Loki::AssocVector and/or hash_map (most of STL implementations have this one).
|
126,279 | 126,285 | C99 stdint.h header and MS Visual Studio | To my amazement I just discovered that the C99 stdint.h is missing from MS Visual Studio 2003 upwards. I'm sure they have their reasons, but does anyone know where I can download a copy? Without this header I have no definitions for useful types such as uint32_t, etc.
| Turns out you can download a MS version of this header from:
https://github.com/mattn/gntp-send/blob/master/include/msinttypes/stdint.h
A portable one can be found here:
http://www.azillionmonkeys.com/qed/pstdint.h
Thanks to the Software Ramblings blog.
NB: The Public Domain version of the header, mentioned by Michael ... |
126,297 | 126,446 | Automatic Casts redux | After I messed up the description of my previous post on this I have sat down and tried to convey my exact intent.
I have a class called P which performs some distinct purpose. I also have PW which perform some distinct purpose on P. PW has no member variables, just member functions.
From this description you would ass... | You could try overriding operator* and operator-> to return access to the embedded p.
Something like this might do the trick :
class P
{
public:
void a( ) { std::cout << "a" << std::endl; }
};
class PW
{
public:
PW(P& p) : p(p) { }
void b( ) { std::cout << "b" << std::endl; }
P & operator*() { r... |
126,751 | 127,108 | Compilation fails randomly: "cannot open program database" | During a long compilation with Visual Studio 2005 (version 8.0.50727.762), I sometimes get the following error in several files in some project:
fatal error C1033: cannot open program database 'v:\temp\apprtctest\win32\release\vc80.pdb'
(The file mentioned is either vc80.pdb or vc80.idb in the project's temp dir.)
T... | It is possible that an antivirus or a similar program is touching the pdb file on write - an antivirus is the most likely suspect in this scenario. I'm afraid that I can only give you some general pointers, based on my past experience in setting nightly builds in our shop. Some of these may sound trivial, but I'm inclu... |
126,800 | 126,847 | Is there a way to determine if an exception is occurring? | In a destructor, is there a way to determine if an exception is currently being processed?
| You can use std::uncaught_exception(), but it might not do what you think it does: see GoTW#47 for more information.
|
126,966 | 127,182 | Is there a good lightweight multiplatform C++ timer queue? | What I'm looking for is a simple timer queue possibly with an external timing source and a poll method (in this way it will be multi-platform). Each enqueued message could be an object implementing a simple interface with a virtual onTimer() member function.
| Boost::ASIO contains an asynchronous timer implementation. That might work for you.
|
127,290 | 128,221 | Is it possible to subclass a C struct in C++ and use pointers to the struct in C code? | Is there a side effect in doing this:
C code:
struct foo {
int k;
};
int ret_foo(const struct foo* f){
return f.k;
}
C++ code:
class bar : public foo {
int my_bar() {
return ret_foo( (foo)this );
}
};
There's an extern "C" around the C++ code and each code is inside its own compilation u... | This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.
There is one caveat here. There is no guarantee o... |
127,426 | 127,516 | GNU compiler warning "class has virtual functions but non-virtual destructor" | I have defined an interface in C++, i.e. a class containing only pure virtual functions.
I want to explicitly forbid users of the interface to delete the object through a pointer to the interface, so I declared a protected and non-virtual destructor for the interface, something like:
class ITest{
public:
virtual vo... | It's more or less a bug in the compiler. Note that in more recent versions of the compiler this warning does not get thrown (at least in 4.3 it doesn't). Having the destructor be protected and non-virtual is completely legitimate in your case.
See here for an excellent article by Herb Sutter on the subject. From the ar... |
127,514 | 127,520 | Resizing Controls in MFC | I am writing a program which has two panes (via CSplitter), however I am having problems figuring out out to resize the controls in each frame. For simplicity, can someone tell me how I would do it for a basic frame with a single CEdit control?
I'm fairly sure it is to do with the CEdit::OnSize() function... But I'm n... | When your frame receives an OnSize message it will give you the new width and height - you can simply call the CEdit SetWindowPos method passing it these values.
Assume CMyPane is your splitter pane and it contains a CEdit you created in OnCreate called m_wndEdit:
void CMyPane::OnSize(UINT nType, int cx, int cy)
{
... |
127,608 | 276,671 | What are the access restrictions on accessing a DSN | We are running part of our app as a windows service and it needs to b able to access DSNs in order to import through ODBC. However there seem to be a lot of restrictions found through trial and error on what DSNs it can access. For example it seems that it cannot
1. access a system DSN unless the account that is run... | This is somewhere between your #1 and #2: sometimes correct file permissions are also necessary. I once had troubles on a Vista machine connecting to a DB2 DSN because, for whatever reason (maybe to write out temp files; although I don't know why it would do such a thing in this location instead of a user-specific on... |
129,919 | 130,025 | Populating a database with file names from directories | I have an application which behaves as a slideshow for all pictures in a folder. It is written in Borland's C++ Builder (9). It currently uses some borrowed code to throw the filenames into a listbox and save the listbox items as a text file.
I want to update this so that the filenames are stored in a proper database ... | You basically neeed to write a recursive function with a TDataSet parameter.
(I could not compile my code, so you get it "as is")
void AddFiles(AnsiString path, TDataSet *DataSet)
{
TSearchRec sr;
int f;
f = FindFirst(path+"\\*.*", faAnyFile, sr);
while( !f )
{
if(sr.Attr & faDirectory)
{
... |
130,117 | 130,123 | If you shouldn't throw exceptions in a destructor, how do you handle errors in it? | Most people say never throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that "the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails... There is really no good wa... | Throwing an exception out of a destructor is dangerous.
If another exception is already propagating the application will terminate.
#include <iostream>
class Bad
{
public:
// Added the noexcept(false) so the code keeps its original meaning.
// Post C++11 destructors are by default `noexcept(true)` ... |
130,237 | 130,255 | How to package a Linux binary for my Open Source application? | I have an Open Source app and I currently only post the binary for the Windows build. At this point Linux users have to get the source and compile it. Is there a standard way for posting a Linux binary?
My app is in c / c++ and compiled with gcc, the only external Linux code I use is X Windows and CUPS.
| The most common way would be to package it in a .rpm file for RedHat-based distros like Fedora, or a .deb file for Debian-based distros like Ubuntu.
|
130,322 | 130,528 | How do you pass a member function pointer? | I am trying to pass a member function within a class to a function that takes a member function class pointer. The problem I am having is that I am not sure how to properly do this within the class using the this pointer. Does anyone have suggestions?
Here is a copy of the class that is passing the member function:
c... | To call a member function by pointer, you need two things: A pointer to the object and a pointer to the function. You need both in MenuButton::SetButton()
template <class object>
void MenuButton::SetButton(int xPos, int yPos, LPCWSTR normalFilePath,
LPCWSTR hoverFilePath, LPCWSTR pressedFilePath,
int Wi... |
130,664 | 130,743 | Combining two executables | I have a command line executable that alters some bits in a file that i want to use from my program.
Is it possible to create my own executable that uses this tool and distribute only one executable?
[edit] Clarification:
The command line tool takes an offset and some bits and changes the bits at this offset in a given... | It would be easier to roll your own implementation of this program than to write the wrapper; it sounds like it is trivial -- just open the file, seek to the right location, write your bits, close the file, you're done.
|
130,800 | 130,885 | Data visualization in desktop applications | I would like to create data visualizations in desktop apps, using frameworks, languages and libraries that help with this kind of task. Visualizations should be interactive: clickable, draggable, customizable, animated...
What I would like to create is something similar to the examples seen here: http://www.visualcompl... | Your post has far too many questions in it to be answered easily in one response, so you might try re-posting with specific questions. Data visualization is a HUGE area of study and it's not significantly different for web applications versus desktop applications.
Put simply, it's the display of data in a way that vis... |
130,913 | 130,926 | What is the state of C++ refactor support in Eclipse? | Is it at the state where it is actually useful and can do more than rename classes?
| CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings
* Declare Method
* Extract Baseclass
* Extract Constant
* Extract Method
* Extract Subclass
* Hide Method
* Implement Method
* Move Field / Method
* Replace Number
* Separate Class
* Generate Getters and Setters
There is a CDT refactor... |
131,241 | 131,271 | Why use iterators instead of array indices? | Take the following two lines of code:
for (int i = 0; i < some_vector.size(); i++)
{
//do stuff
}
And this:
for (some_iterator = some_vector.begin(); some_iterator != some_vector.end();
some_iterator++)
{
//do stuff
}
I'm told that the second way is preferred. Why exactly is this?
| The first form is efficient only if vector.size() is a fast operation. This is true for vectors, but not for lists, for example. Also, what are you planning to do within the body of the loop? If you plan on accessing the elements as in
T elem = some_vector[i];
then you're making the assumption that the container ha... |
131,445 | 131,689 | C++ tr1 on GCC 3.4.4 (for the Nokia N810 tablet computer) | What does it take to get C++ tr1 members (shared_ptr especially, but we'd like function and bind and ALL the others) working with GCC 3.4.4 (for the Nokia N810 tablet computer).
Has anyone done this? Attempted this?
It may not be feasible for us to upgrade to GCC 4.x to cross-compile for this device (but if you've... | For shared_ptr from boost, at least, the number of dependencies is pretty small. You can use bcp to extract subsets from boost as well, so you don't need the whole of boost to compile your application.
|
131,803 | 131,833 | unsigned int vs. size_t | I notice that modern C and C++ code seems to use size_t instead of int/unsigned int pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings.
| The size_t type is the unsigned integer type that is the result of the sizeof operator (and the offsetof operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).
The size_t type may be bigger than, equal to, or smaller than an unsign... |
132,039 | 132,119 | How to send Email through a C++ program? | How can I send an email from C++? Is there a good cross-platform (MS Windows, Linux etc) library that I can use? I'm using GCC (cygwin on MS Windows).
| Check out jwSMTP - a cross-platform SMTP class.
http://johnwiggins.net/jwsmtp/
|
132,116 | 132,148 | Heisenbug: WinApi program crashes on some computers | Please help! I'm really at my wits' end.
My program is a little personal notes manager (google for "cintanotes").
On some computers (and of course I own none of them) it crashes with an unhandled exception just after start.
Nothing special about these computers could be said, except that they tend to have AMD CPUs.
En... | So it doesnnt crash when configuration is DEBUG Configuration? There are many things different than a RELEASE configruation:
1.) Initialization of globals
2.) Actual machine Code generated etc..
So first step is find out what are exact settings for each parameter in the RELEASE mode as compared to the DEBUG mode.
-AD
|
132,242 | 132,308 | Does a memory leak at unload of a DLL cause a leak in the host process? | Consider this case:
dll = LoadDLL()
dll->do()
...
void do() {
char *a = malloc(1024);
}
...
UnloadDLL(dll);
At this point, will the 1k allocated in the call to malloc() be available to the host process again?
The DLL is statically linking to the CRT.
| No, you do not leak.
If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe)
This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT.
If you'd linked with ... |
132,323 | 132,423 | Obtain an index into a vector using Iterators | When iterating over elements of a vector it is preferred to use iterators instead of an index (see Why use iterators instead of array indices?).
std::vector<T> vec;
std::vector<T>::iterator it;
for ( it = vec.begin(); it != vec.end(); ++it )
{
// do work
}
However, it can be necessary to use the index in the body ... | If you're planning on using exclusively a vector, you may want to switch back to the indexed loop, since it conveys your intent more clearly than iterator-loop. However, if evolution of your program in the future may lead to a change of container, you should stick to the iterators and use std::distance, which is guaran... |
132,358 | 132,394 | How to read file content into istringstream? | In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information.
My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (s... | std::ifstream has a method rdbuf(), that returns a pointer to a filebuf. You can then "push" this filebuf into your stringstream:
#include <fstream>
#include <sstream>
int main()
{
std::ifstream file( "myFile" );
if ( file )
{
std::stringstream buffer;
buffer << file.rdbuf();
fil... |
132,612 | 132,917 | Show a ContextMenuStrip without it showing in the taskbar | I have found that when I execute the show() method for a contextmenustrip (a right click menu), if the position is outside that of the form it belongs to, it shows up on the taskbar also.
I am trying to create a right click menu for when clicking on the notifyicon, but as the menu hovers above the system tray and not i... | Try assigning your menu to the ContextMenuStrip property of NotifyIcon rather than showing it in the mouse click handler.
|
132,667 | 132,730 | How can I disable #pragma warnings? | While developing a C++ application, I had to use a third-party library which produced a huge amount of warnings related with a harmless #pragma directive being used.
../File.hpp:1: warning: ignoring #pragma ident
In file included from ../File2.hpp:47,
from ../File3.hpp:57,
from File4.h... | I believe you can compile with
-Wno-unknown-pragmas
to suppress these.
|
132,738 | 132,915 | Why should I ever use inline code? | I'm a C/C++ developer, and here are a couple of questions that always baffled me.
Is there a big difference between "regular" code and inline code?
Which is the main difference?
Is inline code simply a "form" of macros?
What kind of tradeoff must be done when choosing to inline your code?
Thanks
|
Is there a big difference between "regular" code and inline code?
Yes and no. No, because an inline function or method has exactly the same characteristics as a regular one, most important one being that they are both type safe. And yes, because the assembly code generated by the compiler will be different; with a ... |
133,364 | 133,468 | How do you handle strings in C++? | Which is your favorite way to go with strings in C++? A C-style array of chars? Or wchar_t? CString, std::basic_string, std::string, BSTR or CComBSTR?
Certainly each of these has its own area of application, but anyway, which is your favorite and why?
| std::string or std::wstring, depending on your needs. Why?
They're standard
They're portable
They can handle I18N
They have performance guarantees (as per the standard)
Protected against buffer overflows and similar attacks
Are easily converted to other types as needed
Are nicely templated, giving you a wide variety o... |
133,679 | 3,573,305 | Determine SLOC and complexity of C# and C++ from .NET | I have been using SourceMonitor on my project for a couple of years to keep records of source-code complexity and basic SLOC (including comments) for C# and C++ components. These are used for external reporting to our customer, so I'm not in a position to argue their merits or lack of.
I've been working on a repositor... | Whilst I never did find a .NET product that can equally parse C# and C++, I did manage to find an easy-to-use product, CODECOUNT that supports those languages and many more.
It has a simple command line, unlike SourceMonitor that was being used on my project up until CODECOUNT replaced it.
|
133,837 | 135,367 | c++ boost lambda libraries | What might be the best way to start programming using boost lambda libraries.
| Remaining within the boundaries of the C++ language and libraries, I would suggest first getting used to programming using STL algorithm function templates, as one the most common use you will have for boost::lambda is to replace functor classes with inlined expressions inlined.
The library documentation itself gives y... |
133,948 | 136,390 | Sharing GDI handles between processes in Windows CE 6.0 | I know that GDI handles are unique and process specific in 'Big Windows' but do they work the same way in Windows CE 6.0?
For example:
I've got a font management service that several other services and applications will be using. This service has a list of valid fonts and configurations for printing and displaying; Cre... | I believe you are correct, you cannot rely on HFONTs being safe to pass across processes.
'The reason I ask, is that I've seen HFONTs passed to another application through PostMessage work correctly, but I didn't think they were 'supposed' to.'
They were not passed correctly, so there is no 'supposed to'. While HFON... |
134,371 | 134,445 | How Do You Write Code That Is Safe for UTF-8? | We have a set of applications that were developed for the ASCII character set. Now, we're trying to install it in Iceland, and are running into problems where the Icelandic characters are getting screwed up.
We are working through our issues, but I was wondering: Is there a good "guide" out there for writing C++ code... | This looks like a comprehensive quick guide:
http://www.cl.cam.ac.uk/~mgk25/unicode.html
|
134,526 | 134,606 | How do I know I reached a file's maximum size when using ofstream? | While writing a file using ofstream, how do I know when the file's size has reached the OS' maximum file size - more specifically linux's maximum file size - ??
| First off, maximum file size is a filesystem limit, not an Operating System limit. It will even vary for a particular filesystem, based on how the filesystem was formatted.
As for how you'd figure out that you'd reached the limit, your code will likely throw an exception when that happens, which you'll then be able to... |
134,569 | 134,640 | c++ exception : throwing std::string | I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a std::string pointer?
Here's what I was looking forward to doing:
void Foo::Bar() {
if(!QueryPerformanceTimer(&m_baz)) {
throw new std::string("it's the end of the world!");
}
}
void F... | Yes. std::exception is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent document on good style for exceptions and error handling. It's... |
134,731 | 134,777 | Returning a const reference to an object instead of a copy | Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:
class foo
{
private:
std::string name_;
public:
std::string name()
{
return name_;
}
};
Surely the getter would be better returning a const std::string&? The current met... | The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this:
foo *pFoo = new foo;
const std::string &myName = pFoo->getName();
delete pFoo;
cout << myName; // error! dangling reference
However, since your exist... |
134,796 | 1,085,245 | Automatically stop Visual C++ 2008 build at first compile error? | I know I can compile individual source files, but sometimes -- say, when editing a header file used by many .cpp files -- multiple source files need to be recompiled. That's what Build is for.
Default behavior of the "Build" command in VC9 (Visual C++ 2008) is to attempt to compile all files that need it. Sometimes t... | I came up with a better macro guys. It stops immediately after the first error/s (soon as build window is updated).
Visual Studio -> Tools -> Macros -> Macro IDE... (or ALT+F11)
Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated
If Not (pPane.Name = ... |
135,069 | 135,454 | #ifdef vs #if - which is better/safer as a method for enabling/disabling compilation of particular sections of code? | This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...
Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:
//---- SomeSourceFile.cpp ----
#define DEBUG_ENA... | My initial reaction was #ifdef, of course, but I think #if actually has some significant advantages for this - here's why:
First, you can use DEBUG_ENABLED in preprocessor and compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using #if, I can write this
DoSomethingSlowWithTimeout(DEBUG... |
135,112 | 137,838 | Java Developer meets Objective-C on Mac OS | I have developed in C++ many years ago, but these days I am primarily a Java software engineer. Given I own an iPhone, am ready to spring for a MacBook next month, and am generally interested in getting started with Mac OS developmentmt (using Objective C), I thought I would just put this question out there: What Next... | Having purchased both of the books in your question, I recommend Cocoa Programming for Mac OS X as a quick way to learn the language and the Cocoa framework, and is probably the fastest way to start producing real applications in Cocoa. I highly recommend it. Programming in Objective-C 2.0 is a great reference book, bu... |
135,129 | 135,152 | Should one prefer STL algorithms over hand-rolled loops? | I seem to be seeing more 'for' loops over iterators in questions & answers here than I do for_each(), transform(), and the like. Scott Meyers suggests that stl algorithms are preferred, or at least he did in 2001. Of course, using them often means moving the loop body into a function or function object. Some may fee... | It depends on:
Whether high-performance is required
The readability of the loop
Whether the algorithm is complex
If the loop isn't the bottleneck, and the algorithm is simple (like for_each), then for the current C++ standard, I'd prefer a hand-rolled loop for readability. (Locality of logic is key.)
However, now th... |
135,634 | 135,684 | Class design vs. IDE: Are nonmember nonfriend functions really worth it? | In the (otherwise) excellent book C++ Coding Standards, Item 44, titled "Prefer writing nonmember nonfriend functions", Sutter and Alexandrescu recommend that only functions that really need access to the members of a class be themselves members of that class. All other operations which can be written by using only mem... | I'm going to have to disagree with Sutter and Alexandrescu on this one. I think if the behavior of function foo() falls within the realm of class Bar's responsibilities, then foo() should be part of bar().
The fact that foo() doesn't need direct access to Bar's member data doesn't mean it isn't conceptually part of Ba... |
135,834 | 135,966 | Python: SWIG vs ctypes | In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). What are the performance metrics of the two?
| SWIG generates (rather ugly) C or C++ code. It is straightforward to use for simple functions (things that can be translated directly) and reasonably easy to use for more complex functions (such as functions with output parameters that need an extra translation step to represent in Python.) For more powerful interfacin... |
136,050 | 1,910,905 | Prevent visual studio creating browse info (.ncb) files | Is there a way to prevent VS2008 creating browse info file files for C++ projects.
I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed.
EDIT - it's also needed for go to declaration/definition
| There is a registry key for this as well: [HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++]
Intellisense ON
"IntellisenseOptions"=dword:00000000
Intellisense OFF
"IntellisenseOptions"=dword:00000007
Intellisense ON - NO Background UPDATE
"IntellisenseOptions"=dword:00000005
Mo... |
136,175 | 136,714 | Fastest small datastore on Windows | My app keeps track of the state of about 1000 objects. Those objects are read from and written to a persistent store (serialized) in no particular order.
Right now the app uses the registry to store each object's state. This is nice because:
It is simple
It is very fast
Individual object's state can be read/writte... | If you do begin to experiment with SQLite, you should know that "out of the box" it might not seem as fast as you would like, but it can quickly be made to be much faster by applying some established optimization tips:
SQLite optimization
Depending on the size of the data and the amount of RAM available, one of the bes... |
136,548 | 136,695 | Pro/con: Initializing a variable in a conditional statement | In C++ you can initialize a variable in an if statement, like so:
if (CThing* pThing = GetThing())
{
}
Why would one consider this bad or good style? What are the benefits and disadvantages?
Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is... | The important thing is that a declaration in C++ is not an expression.
bool a = (CThing* pThing = GetThing()); // not legit!!
You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.
if(A *a = new A)
{
// this is legit and a ... |
136,703 | 137,117 | Is there a one-liner to read in a file to a string in C++? | I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++.
Equivalent of this if you know Cocoa:
NSString *string = [NSString stringWithContentsOfFile:file];
| We can do it but it's a long line :
#include<fstream>
#include<iostream>
#include<iterator>
#include<string>
using namespace std;
int main()
{
// The one-liner
string fileContents(istreambuf_iterator<char>(ifstream("filename.txt")), istreambuf_iterator<char>());
// Check result
cout << fileContents;
... |
136,880 | 136,917 | Sell me on const correctness | So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few... | This is the definitive article on "const correctness": https://isocpp.org/wiki/faq/const-correctness.
In a nutshell, using const is good practice because...
It protects you from accidentally changing variables that aren't intended be changed,
It protects you from making accidental variable assignments, and
The compi... |
136,946 | 136,954 | Difference between Enum and Define Statements | What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?
For example, when should one use
enum {BUFFER = 1234};
over
#define BUFFER 1234
| enum defines a syntactical element.
#define is a pre-preprocessor directive, executed before the compiler sees the code, and therefore is not a language element of C itself.
Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for... |
137,038 | 137,074 | How do you get assembler output from C/C++ source in GCC? | How does one do this?
If I want to analyze how something is getting compiled, how would I get the emitted assembly code?
| Use the -S option to gcc (or g++), optionally with -fverbose-asm which works well at the default -O0 to attach C names to asm operands as comments. It works less well at any optimization level, which you normally want to use to get asm worth looking at.
gcc -S helloworld.c
This will run the preprocessor (cpp) over hel... |
137,089 | 137,175 | Boost::signal memory access error | I'm trying to use boost::signal to implement a callback mechanism, and I'm getting a memory access assert in the boost::signal code on even the most trivial usage of the library. I have simplified it down to this code:
#include <boost/signal.hpp>
typedef boost::signal<void (void)> Event;
int main(int argc, char* argv... | I've tested your code on my system, and it works fine. I think that there's a mismatch between your compiler, and the compiler that your Boost.Signals library is built on. Try to download the Boost source, and compile Boost.Signals using the same compiler as you use for building your code.
Just for my info, what compil... |
137,258 | 137,264 | std::map iteration - order differences between Debug and Release builds | Here's a common code pattern I have to work with:
class foo {
public:
void InitMap();
void InvokeMethodsInMap();
static void abcMethod();
static void defMethod();
private:
typedef std::map<const char*, pMethod> TMyMap;
TMyMap m_MyMap;
}
void
foo::InitMap()
{
m_MyMap["abc"] = &foo::abcMethod... | Don't use const char* as the key for maps. That means the map is ordered by the addresses of the strings, not the contents of the strings. Use a std::string as the key type, instead.
std::map is not a hash table, it's usually implemented as a red-black tree, and elements are guaranteed to be ordered by some criteria (b... |
137,282 | 139,329 | How can I avoid the Diamond of Death when using multiple inheritance? | http://en.wikipedia.org/wiki/Diamond_problem
I know what it means, but what steps can I take to avoid it?
| A practical example:
class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};
Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.
To solve this, we need virtual inheritance. It's class A ... |
137,659 | 137,682 | Persistence of std::map in C++ | Do you know any easy or simple way to make a map object (from the STL library) persistent (i.e. write it to a file) so that you can recover its state later when the program in run later ??
Thanks for your help
| I believe the Boost Serialization library is capable of serializing std::map, but the standard library itself provides no means. Serialization is a great library with a lot of features and is easy to use and to extend to your own types.
|
137,812 | 137,820 | What's your favorite C++0x feature? | As many of us know (and many, many more don't), C++ is currently undergoing final drafting for the next revision of the International Standard, expected to be published in about 2 years. Drafts and papers are currently available from the committee website. All sorts of new features are being added, the biggest being co... | auto keyword for variable type inferencing
|
138,122 | 138,143 | How to create a very big bitmap in C++/MFC / GDI | I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver.
I'm currently using a bi... | CDC and CBitmap appears to only support device dependant bitmaps, you might have more luck creating your bitmap with ::CreateDIBSection, then attaching a CBitmap to that. The raw GDI interfaces are a little hoary, unfortunately.
You probably won't have much luck with 20,000 x 20,000 at 32 BPP, at least in a 32-bit appl... |
138,153 | 3,761,803 | Is ncurses available for windows? | Are there any ncurses libraries in C/C++ for Windows that emulate ncurses in native resizable Win32 windows (not in console mode)?
| There's an ongoing effort for a PDCurses port:
http://www.mail-archive.com/pdcurses-l@lightlink.com/msg00129.html
http://www.projectpluto.com/win32a.htm
|
138,361 | 138,406 | How much faster is C++ than C#? | Or is it now the other way around?
From what I've heard there are some areas in which C# proves to be faster than C++, but I've never had the guts to test it by myself.
Thought any of you could explain these differences in detail or point me to the right place for information on this.
| There is no strict reason why a bytecode based language like C# or Java that has a JIT cannot be as fast as C++ code. However C++ code used to be significantly faster for a long time, and also today still is in many cases. This is mainly due to the more advanced JIT optimizations being complicated to implement, and the... |
138,466 | 138,505 | Get address of current page in Internet Explorer from toolbar | I'm trying to wrap my head around creating a toolbar (a tool band in a rebar) in MFC for Internet Explorer using COM.
Is it possible to get the address of the currently viewed page (i.e., https://stackoverflow.com/questions/ask in my case :-) ) from the toolbar?
If so, what should I look in to?
Thanks!
| You can use the IWebBrowser2::get_LocationURL method.
|
138,917 | 139,152 | Visual Studio debugger slows down in in-line code | Since I upgraded to Visual Studio 2008 from vs2005, I have found a very annoying behaviour when debugging large projects. If I attempt to step into inline code, the debugger appears to lock up for tens of seconds. Each time that I step inside such a function, there is a similar pause. Has anyone experienced this and... | I used to get this - I think it's a bug with the 'Autos' debug window:
http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/eabc58b1-51b2-49ce-b710-15e2bf7e7516/
|
138,952 | 139,733 | Is there an implementation for Delphi:TClientDataSet in C++ for MVS? | I want to migrate from Embarcadero Delphi to Visual Studio, but without a TClientDataset class it is very difficult.
This class represents an in-memory dataset.
I can't find any class like TClientDataset.
Can anyone help me find something like this please?
| Visual studio has DataSet and DataTable classes which are very close to what a TClientDataSet is in Delphi.
See http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx
|
139,325 | 139,377 | Setting all values in a std::map | How to set all the values in a std::map to the same value, without using a loop iterating over each value?
| Using a loop is by far the simplest method. In fact, it’s a one-liner:[C++17]
for (auto& [_, v] : mymap) v = value;
Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use std::fill.
To use them anyway (pre-C++20), we need to write adapters — in the... |
139,622 | 139,632 | Does the CAutoPtr class implement reference counting? | Modern ATL/MFC applications now have access to a new shared pointer class called CAutoPtr, and associated containers (CAutoPtrArray, CAutoPtrList, etc.).
Does the CAutoPtr class implement reference counting?
| Having checked the CAutoPtr source, no, reference counting is not supported. Using boost::shared_ptr instead if this ability is required.
|
139,668 | 140,387 | Why would the Win32 OleGetClipboard() function return CLIPBRD_E_CANT_OPEN? | Under what circumstances will the Win32 API function OleGetClipboard() fail and return CLIPBRD_E_CANT_OPEN?
More background: I am assisting with a Firefox bug fix. Details here:
bug 444800 - cannot retrieve image data from clipboard in lossless format
In the automated test that I helped write, we see that OleGetClipb... | The documentation says that OleGetClipboard can fail with this error code if OpenClipboard fails. In turn, if you read that documentation, it says:
"OpenClipboard fails if another window has the clipboard open."
It's an exclusive resource: only one window can have the clipboard open at a time. Basically, if you can't d... |
139,705 | 673,642 | Indirect Typelib not imported well from Debug dll | Using VC2005, I have 3 projects to build:
libA (contains a typelib, results in libA.dll): IDL has a line library libA { ...
libB (contains a typelib importing libA, results in libB.dll): IDL has a line importlib( "libA " );
libC (imports libB): one of the source files contains #import <libB.dll>
the #import <libB.d... | Finally Found It!
In the Visual Studio project, the A.idl file in LibA had the MkTypeLib Compatible setting ON. This overruled the behaviour inherited from the A project. To make things worse, it was only ON in the Debug configuration.
The consequence was that for every
typedef [public] tagE enum { cE1, cE2 } eE;
Th... |
139,826 | 140,352 | Track Data Execution Prevention (DEP) | When running one of our software, a tester was faced with the data execution prevention dialog of Windows.
We try to reproduce this situation on a developer computer for debugging purposes : with no success.
Does anyone know how to find what may cause the DEP protection to kill the application?
Is there any existing to... | The DEP dialog will typically only show when you try to execute code from a region that you're not marking as executable. This might be caused by 'thunks' in a library you're using, e.g. ATL windowing. This problem is fixed in ATL 8.0.
A stack-trashing bug - for example, a buffer overrun - can also cause this problem, ... |
140,033 | 140,048 | boost::shared_ptr standard container | Assume I have a class foo, and wish to use a std::map to store some boost::shared_ptrs, e.g.:
class foo;
typedef boost::shared_ptr<foo> foo_sp;
typeded std::map<int, foo_sp> foo_sp_map;
foo_sp_map m;
If I add a new foo_sp to the map but the key used already exists, will the existing entry be deleted? For example:
f... | First off, your question title says boost::auto_ptr, but you actually mean boost::shared_ptr
And yes, the original pointer will be freed (if there are no further shared references to it).
|
140,061 | 140,100 | When to use dynamic vs. static libraries | When creating a class library in C++, you can choose between dynamic (.dll, .so) and static (.lib, .a) libraries. What is the difference between them and when is it appropriate to use which?
| Static libraries increase the size of the code in your binary. They're always loaded and whatever version of the code you compiled with is the version of the code that will run.
Dynamic libraries are stored and versioned separately. It's possible for a version of the dynamic library to be loaded that wasn't the origina... |
140,347 | 140,373 | Win32/MFC Get window rect from client rect | I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!
Does anyone know what it is?
It will do something similar to:
const CRect client(0, 0, 200, 200);
const CRect window = ClientRectToWindowRect(client);
SetWindowPos(...)... | You're probably thinking of AdjustWindowRectEx(). Keep in mind, this is intended for use when creating a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use GetWindowRect().
|
140,786 | 140,865 | How to simplify this code (generates a random int between min and max base on unsigned int)? | The code is
return min + static_cast<int>(static_cast<double>(max - min + 1.0) *
(number / (UINT_MAX + 1.0)));
number is a random number obtained by rand_s. min and max are ints and represent minimum and maximum values (inclusive).
If you provide a solution not using unsigned int as a number, please also explain how... | The static_cast<double> is redundant because the "+1.0"s will cause promotion to double anyway.
|
140,935 | 140,944 | Partial class definition on C++? | Anyone knows if is possible to have partial class definition on C++ ?
Something like:
file1.h:
class Test {
public:
int test1();
};
file2.h:
class Test {
public:
int test2();
};
For me it seems quite useful for definining multi-platform classes that have common functions between them tha... | This is not possible in C++, it will give you an error about redefining already-defined classes. If you'd like to share behavior, consider inheritance.
|
141,337 | 141,380 | Should I store entire objects, or pointers to objects in containers? | Designing a new system from scratch. I'll be using the STL to store lists and maps of certain long-live objects.
Question: Should I ensure my objects have copy constructors and store copies of objects within my STL containers, or is it generally better to manage the life & scope myself and just store the pointers to ... | Since people are chiming in on the efficency of using pointers.
If you're considering using a std::vector and if updates are few and you often iterate over your collection and it's a non polymorphic type storing object "copies" will be more efficent since you'll get better locality of reference.
Otoh, if updates are c... |
141,498 | 285,538 | What open source C++ static analysis tools are available? | Java has some very good open source static analysis tools such as FindBugs, Checkstyle and PMD. Those tools are easy to use, very helpful, runs on multiple operating systems and free.
Commercial C++ static analysis products are available. Although having such products are great, the cost is just way too much for stude... | Oink is a tool built on top of the Elsa C++ front-end. Mozilla's Pork is a fork of Elsa/Oink.
See: http://danielwilkerson.com/oink/index.html
|
141,752 | 141,772 | Float values behaving differently across the release and debug builds | My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values ar... | Release mode may have a different FP strategy set. There are different floating point arithmetic modes depending on the level of optimization you'd like. MSVC, for example, has strict, fast, and precise modes.
|
141,864 | 141,926 | Operator overloading for C++ maps | I need help understanding some C++ operator overload statements. The class is declared like this:
template <class key_t, class ipdc_t>
class ipdc_map_template_t : public ipdc_lockable_t
{
...
typedef map<key_t,
ipdc_t*,
less<key_t>> map_t;
...
The creator of the class has created ... | These are typecast operators, so you can do this:
{
key_t key = iter;
ipdc_t *val = iter;
}
Or, since ipdc_map_template::iterator is a subclass of std::map::iterator, you can still use the original accessors (which I find more readable):
{
key_t key = (*iter).first;
ipdc_t *val = (*iter).second;
... |
142,016 | 142,023 | C/C++ Structure offset | I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.
IE: given
struct mstct {
int myfield;
int myfield2;
};
I could write:
mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));
And get offset 4 for ... | How about the standard offsetof() macro (in stddef.h)?
Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:
#define OFFSETOF(type, field) ((unsigned long) &(((type *) 0)->field))
|
142,240 | 142,402 | Explicit code parallelism in c++ | Out of order execution in CPUs means that a CPU can reorder instructions to gain better performance and it means the CPU is having to do some very nifty bookkeeping and such. There are other processor approaches too, such as hyper-threading.
Some fancy compilers understand the (un)interrelatedness of instructions to a... | It sounds like you ran into the same problem chip designers face: Executing a single instruction takes a lot of effort, but it involves a bunch of different steps that can be strung together in an execution pipeline. (It is easier to execute things in parallel when you can build them out of separate blocks of hardware.... |
142,331 | 142,475 | Resources for high performance computing in C++ | I'm looking for books or online resources that go in detail over programming techniques for high performance computing using C++.
| practically all HPC code I've heard of is either for solving sytems of linear equations or FFT's. Heres some links to start you off at least in the libraries used:
BLAS - standard set of routines for linear algebra - stuff like matrix multiplication
LAPACK - standard set of higher level linear algebra routines - stuff... |
142,391 | 142,401 | Getting a boost::shared_ptr for this | I am making extensive use of boost:shared_ptr in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr. Unfortunately this means that I can't pass this into any function that takes a shared_ptr. Consider this code:
void bar(boost::shared_ptr<Foo> pFoo)
{
...
}
void Foo::some... | You can derive from enable_shared_from_this and then you can use "shared_from_this()" instead of "this" to spawn a shared pointer to your own self object.
Example in the link:
#include <boost/enable_shared_from_this.hpp>
class Y: public boost::enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.