question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,751,862 | 1,752,119 | Need help understanding using C++ map as an associative array | I was going through Josuttis's "Using Map's as associative arrays" (from The C++ Standard Library - A Tutorial and Reference, 2nd Edition) and came across Using a std::map as an associative array on Stack Overflow. Now I have more questions on the constructors that are called when inserting into a map.
Here is my sampl... | If you read the specification for std::map, it says that operator[] is equivalent to (in this case)
(*((this->insert(make_pair(1,C()))).first)).second
So this explains all the constructor calls you see. First it calls the default constructor C(). Then it calls make_pair, which copies the C object. Then it calls insert... |
1,751,915 | 1,751,979 | Template function with dependent type parameters within template class | I've been trying to do this simple stuff and Visual studio 2008 does not seems to like it.
template <class CharType>
class SomeClass
{
public:
template <class T1, class T2>
static bool SomeOperator(const typename T1::const_iterator& p_Begin1,
const typename T1::const_iterator& p_End... | The compiler is simply unable to deduce types from this context.
Suppose std::wstring::const_iterator is actually const wchar_t*, which is likely. In that case, how does the compiler know it should substitute std::wstring rather than any other type T with T::const_iterator being const wchar_t* (perhaps vector<wchar_t>)... |
1,752,261 | 1,753,271 | Memory leak using multiple boost::connect on single slot_type | I'm using boost::signals and leaking memory when I try to connect multiple signals to a single slot_type. I've seen this same leak reported on various forums, but can't find any that mention the correct way to do this, or any workaround.
What I am trying to do:
I am trying to pass the result of boost::bind() into a fu... | I'm pretty sure it's a bug. If you collapse it down to a tiny example, e.g.:
void boundFunction(int) { }
typedef boost::signal0<void> LeakSignalType;
LeakSignalType::slot_type aSlot = boost::bind(&::boundFunction, 1);
LeakSignalType sig1, sig2;
sig1.connect(aSlot);
sig2.connect(aSlot);
and trace the allocations, you'... |
1,752,319 | 1,752,875 | How best to manage Linux's buffering behavior when writing a high-bandwidth data stream? | My problem is this: I have a C/C++ app that runs under Linux, and this app receives a constant-rate high-bandwith (~27MB/sec) stream of data that it needs to stream to a file (or files). The computer it runs on is a quad-core 2GHz Xeon running Linux. The filesystem is ext4, and the disk is a solid state E-SATA driv... | You can use the posix_fadvise() with the POSIX_FADV_DONTNEED advice (possibly combined with calls to fdatasync()) to make the system flush the data and evict it from the cache.
See this article for a practical example.
|
1,752,347 | 1,752,565 | Define a struct in a midl generated header file | I am in the process of automating the build of a legacy product and have hit a wall...
I have a .idl file that is compiled in VC++ 6.0 using midl to generate a .tlb, .h and .c file that has a manual build step to add:
struct StructDef;
Just ahead of an MIDL_INTERFACE in the generated .h file. The rest of the .h file ... | #pragma midl_echo instructs MIDL to insert an arbitrary piece of text into the generated header file. You can use it like this:
#pragma midl_echo("struct StructDef;")
It appears that the cpp_quote attribute provides similar functionality.
Alternatively, if you have Cygwin installed, you may find it simpler (or just p... |
1,752,557 | 1,752,804 | Is it possible to compile ImageMagick with custom libxml2 on the Mac | It always seems to pick up the version from /usr/lib and there doesn't seem to be a ./configure parameter to override it.
./configure --prefix=$PREFIX --with-quantum-depth=8 --disable-installed --without-x --without-perl --enable-static --disable-shared --with-jpeg --with-tiff CPPFLAGS="$CPPFLAGS" LDFLAGS="$LDFLAGS" CF... | Generally, an installation of libxml2 includes a configuration script xml2-config that users of the library use to find the correct paths to its components and other build info. The Apple-supplied version of libxml2 has xml2-config in /usr/bin. If you've installed another version of libxml2, make sure your $PATH is s... |
1,752,589 | 1,752,653 | Question about send / recv | New to socket programming. Got a couple questions:
My program is really inconsistent with its output. Sometimes my client receives, sometimes it doesnt. I am also using the same input each time.
Just need confirmation: Can the number of bytes received be less than the number of bytes sent from the server?
How do I mak... |
Assuming this is TCP (not UDP), you can think of the socket as a stream of bytes. The sender can put them in in whatever way he wants, and you can get them out in whatever way you want. So the sender could write a 1k chunk in one call, and you can receive them a byte at a time if you want.
There are a number of ways, ... |
1,752,897 | 1,752,949 | What is the most efficient implementation of a java like object monitor in C++? | In Java each object has a synchronisation monitor. So i guess the implementation is pretty condensed in term of memory usage and hopefully fast as well.
When porting this to C++ what whould be the best implementation for it. I think that there must be something better then "pthread_mutex_init" or is the object overhead... | The Sun Hotspot JVM implements thin locks using compare and swap. If an object is locked, then the waiting thread wait on the monitor of thread which locked the object. This means you only need one heavy lock per thread.
|
1,753,029 | 1,753,117 | Sun Raster images: Why 1 byte row padding when width is odd? | This may be waaay to specific for SO, but there seems to be a dearth of info on the sun raster standard. (Even JWZ is frustrated by this!)
Intro: The Sun raster standard says that rows of pixels have padding at the end such that the number of bits in a row is a factor of 16 (i.e. an even number of bytes). For example... | I'd say the image loading code in Gimp and ImageMagick has a bug. Simple as that.
Keep in mind that the SUN-Raster format isn't that widely used. It's very possible that you're one of the first who actually tried to use this format, found out that it doesn't work as expected and not ignored it.
If the spec. sais someth... |
1,753,094 | 1,753,123 | C++ segmentation fault when trying to output object functions | I am attempting to output functions common to a set of objects that share a base class and I am having some difficulty. When the objects are instantiated they are stored in an array and then I am attempting with the following code to execute functionality common to all the objects in this loop:
if ( truck <= v ) // ... | dynamic_cast to a pointer type returns a null pointer (aka 0, NULL) if the object isn't of the specified type. You must check the pointer before using it, or use a reference type (which throws an exception on failure instead):
if (Truck* p = dyanmic_cast<Truck*>(vptr[i])) {
// use the pointer here
}
else {
// vptr... |
1,753,182 | 1,753,350 | How to read structured data from file in C++? | I have a data file where I need to read a datum from each line and store it. And then depending on the value of one of those datums store that data in an array so that I can then calculate the median value of all of these data.
The line of data is demographic information and depending on the geographic location, addres... | For comma-delimited input:
using namespace std;
ifstream file;
string line;
while(getline(file, line)) {
istringstream stream(line);
string data[3];
for(int ii = 0; ii < sizeof data / sizeof data[0]; ++ii)
if(!getline(stream, data[ii], ','))
throw std::runtime_error("invalid data");
... |
1,753,357 | 1,753,403 | Per-file enabling of scope guards | Here's a little problem I've been thinking about for a while now that I have not found a solution for yet.
So, to start with, I have this function guard that I use for debugging purpose:
class FuncGuard
{
public:
FuncGuard(const TCHAR* funcsig, const TCHAR* funcname, const TCHAR* file, int line);
~FuncGuard();... | Add a bool to FuncGuard that controls whether it should display anything.
#ifdef NDEBUG
#define SCOPE_TRACE(CAT)
#else
extern bool const func_guard_alloc;
extern bool const func_guard_other;
#define SCOPE_TRACE(CAT) \
NppDebug::FuncGuard npp_func_guard_##__LINE__( \
TEXT(__FUNCSIG__), TEXT(__FUNCTION_... |
1,753,469 | 5,132,081 | How to hook up Boost serialization & iostreams to serialize & gzip an object to string? | I've been using the Boost serialization library, which is actually pretty nice, and lets me make simple wrappers to save my serializable objects to strings, like so:
namespace bar = boost::archive;
namespace bio = boost::iostreams;
template <class T> inline std::string saveString(const T & o) {
std::ostringstream oss... | Returning to this question, I realized I must've fixed it sometime last year (as I'm using saveGZString right now). Digging to see how I fixed it, it was pretty silly/simple:
namespace bar = boost::archive;
namespace bio = boost::iostreams;
template <typename T> inline std::string saveGZString(const T & o) {
... |
1,753,486 | 1,753,494 | Copy constructor for a binary tree C++ | I have a Tree class with the following definition:
class Tree {
Tree();
private:
TreeNode *rootPtr;
}
TreeNode represents a node and has data, leftPtr and rightPtr.
How do I create a copy of a tree object using a copy constructor? I want to do something like:
Tree obj1;
//insert nodes
Tree obj2(obj1); //without m... | Pseudo-code:
struct Tree {
Tree(Tree const& other) {
for (each in other) {
insert(each);
}
}
void insert(T item);
};
Concrete example (changing how you walk the tree is important to know, but detracts from showing how the copy ctor works, and might be doing too much of someone's homework here):
#i... |
1,753,745 | 1,753,757 | Making render method virtual? | I'm starting with C++ in more depth while building a simple 2d game engine. In my engine I have (or want to have) an "Abstract" GameEntity class, which carries the methods draw, update, and maybe position (x, y). I will add more stuff while it occurs to me.
Classes to inherit from GameEntity would be anything that coul... | No, this isn't bad; the overhead isn't that significant (you might consult this answer to another question).
This is, for example, the general approach taken by OpenSceneGraph, an open source scene graph based on OpenGL. OSG has a Node class, from which all node types used in the scene graph are derived, and it uses a... |
1,753,785 | 1,754,202 | Combining function bodies at runtime | This is going to sound super hackish but does anyone know of a way to combine method bodies at runtime in C++? I'm currently on the path of grabbing the address of the functions then memcopy to executable memory but it has the problem of unwanted prolog/epilog.
Essentially I've got a few dozen simple operations that t... | I can't see any practical use for this, except for the heck of it :-)
So first you should decide for a platform.
There is no way in hell you can do this in a cross-platform way.
It might actually be quite difficult to do it in a way that works across several compilers, even on the same platform.
Then the processor type... |
1,754,037 | 1,754,814 | How to add picture box in win32 API using visual c++ | I have a Window (win32 API) Application in visual c++. I am not using MFC. I have to add a picutre box to my application and Change the image of this picture box periodically. Can any one help me out in achieving the above task? Thanks in advance.
| This is quite a complex task to post full code here, but I will try to give a few guidelines on how to do it:
First method is to load the image and paint it
Load your image (unfortunately the plain Win32 API has support for quite a few image formats BMP, ICO ...).
HBITMAP hImage = (HBITMAP)LoadImage(NULL, (LPCSTR)fil... |
1,754,042 | 1,754,059 | was not declared in this scope C++ | Why do I get this error in the code below?
class ST : public Instruction{
public:
ST (string _name, int _value):Instruction(_name,_value){}
void execute(int[]& anArr, int aVal){
//not implemented yet
cout << "im an st" <<endl;
anArr[value] = aVal;
}
virtual Instruction* Clone(){
... | You have a problem with the type of the first parameter of your execute function. Read this up to know more about how to pass arrays around.
|
1,754,295 | 1,754,384 | Search string parser in C/C++ | I work on an open source project focused around Biblical texts. I would like to create a standard string format to build up a search string. I would then need to parse the search string and run the search with the options given. There are a number of different options, from scope of the search, to searching multiple te... | Tools like Lex and Yacc are suitable for your purposes. A parser for a search string is not that different from a parser for a programming language (the big difference is that a search string parser generates rules guiding the search, while the programming language parser generates a parse tree from where code is gener... |
1,754,417 | 1,767,521 | Accessing tabs on Firefox with a C++ XPCOM extension | What XPCOM interfaces should I use to detect opening, closing and switching of tabs and also get their associated URL from a firefox extension?
I have seen instances of code that manage tabs in JS, but how about from C++ ?
| You can write small JS component that will reroute tab events to your C++ component using nsIObserverService.
In C++ code you can use this snippet to register your component as observer to user defined events that is used for rerouting tab events.
NS_IMETHODIMP MyCppComponent::Observe(nsISupports *aSubject,
const c... |
1,754,503 | 1,755,103 | Logging safely from a worker thread? | In one of my worker threads I want to do some logging. The log messages are channeled to a GUI textarea, which should only be accessed from the main thread. So the problem is: how do I log messages safely from a worker thread?
My current solution is to have the logging function check whether we are currently in the mai... | If you have one rule for logging in one thread ("just do it now") and another rule for other threads ("add it to a queue for later") then your logging will get out of order. I can't imagine this being a good thing. Have one rule for all your logging - add it to the queue.
|
1,754,541 | 1,754,580 | Error with parsing string and trying to find '\0' character | I'm trying to get one side to send an error message to client, but client isn't able to parse it correctly.
My error is >>>>> in my parseString function, it lets index = 0 and therefore I get an out of range for my 'substr' call.
Server Side:::
#define ERRBUFSIZE 51
string error = "Error - Already Registered: "... | Why not change your parseString to the following:
string TCPClient::parseString(const string& message, int strLength )
{
cout << "parsing new string" << endl;
string result = message.substr( 0, strLength );
cout << "THE RESULT :: " << result << endl;
return result;
}
And then change the calling code to... |
1,754,787 | 2,318,307 | WMI Error in Windows Server 2008 (WMI Provider) | I've implemented a WMI provider (Window service, Instance, Methods and Properties provider).
It works fine on Windows Server 2003, but when it run on Windows Server 2008 with non-local administrator user, I cannot query it.
The error I get is 0x8004101d - unexpected error.
When the service user is a local admin everyth... | OK, the problem was that I didn't specify the HostingModel, so it defaulted to NetworkServiceHost. The one needed one is LocalSystemHostOrSelfHost (that is the default in prior to Vista OSs).
|
1,754,972 | 1,873,160 | Launching applications silently? | My C++ application calls VLC as a subprocess. Is there a way to avoid having the GUI pop-up? I am looking for a Mac and a Windows solution. Hackish workarounds are welcome too.
PS: I know there is such a thing as cvlc (command-line version of VLC), but I haven't found any builds for it online. You do get it when you ma... | I found the answer. VLC allows you to start without GUI by using:
VLC -I dummy
Starts the "dummy" interface.
VLC -I rc
Starts the "remote control" interface, which allows you to send commands using the stdin channel.
|
1,755,000 | 1,755,070 | Passing around fixed-size arrays in C++? | Basically I'd like to do something like that:
int[3] array_func()
{
return {1,1,1};
}
int main(int argc,char * argv[])
{
int[3] point=array_func();
}
But that doesn't seem legal in C++. I know I can use vectors, but since I know the size of the array is a constant, it seems like a loss of performance is likel... | Using C++0x, the almost finalized new C++ standard (already implemented in latest gcc and msvc IIRC), you can do it exactly as you want! Simply use std::array instead of int[3].
std::array<int, 3> array_func()
{
return {1,1,1};
}
int main(int argc,char * argv[])
{
std::array<int, 3> point = array_func();
}
|
1,755,010 | 1,755,380 | Best way to return early from a function returning a reference | Let us say we have a function of the form:
const SomeObject& SomeScope::ReturnOurObject()
{
if( ! SomeCondition )
{
// return early
return ;
}
return ourObject;
}
Clearly the code above has an issue, if the condition fails then we have a problem as to how to return from this function.... | This isn't a syntactic issue, but a design issue. You have to specify what ReturnOurObject() is supposed to return when SomeCondition is true. That depends mainly on what the function is going to be used for. And that you haven't told us.
Depending on the design issues, I see a few possible syntactic ways out of this:... |
1,755,196 | 1,775,247 | Receive WM_COPYDATA messages in a Qt app | I am working on a Windows-only Qt application, and I need to receive data from a Microsoft OneNote plugin. The plugin is written in C#, and can send WM_COPYDATA messages. How do I receive these messages in a C++ Qt app?
I need to:
Be able to specify the "class name" a window registers as when it calls RegisterClassEx,... | This can all be handled within Qt:
Extend QWidget with a class that will capture the WM_COPYDATA messages:
class EventReceiverWindow : public QWidget
{
Q_OBJECT
public:
EventReceiverWindow();
signals:
void eventData(const QString & data);
private:
bool winEvent ( MSG * message, long * result );
}... |
1,755,392 | 1,755,400 | Supressing warnings for a codeblock using gcc 4.1.2? | I have a section of code that uses a Boost library that results in a lot of these type of warning messages:
class x has virtual functions but non-virtual destructor
Using g++ 4.1.2, how do I temporarily disable warnings for this codeblock then enable them again after it.
Everything I try (pragma gcc diagnostic, etc) s... | Take a look at the -Wno-non-virtual-dtor.
You can restrict this option to affect only certain files.
Can you move your "bad" code to separate c++ file? If so, turn this option only for that file.
|
1,755,639 | 1,756,989 | Is every application using anything dependent on VC++9 runtime required to have a manifest embedded? | I don't get what this article on R6034 says. Looks like it states that every application dependent on VC++9 runtime must have a manifest.
Now we have a DLL that we ship to customers, that depends on VC++9 runtime and has a manifest embedded. Does every application using our DLL also need to have a manifest embedded?
| No, your customers do not need manifests. The loader deals with manifests for every image it loads... so if your DLL has a manifest it will be parsed/applied properly, regardless of how your DLL is loaded.
|
1,756,062 | 1,843,666 | Anyone used libvlc on Mac? | Edit
I've been able to simplify the reproduction of the error:
When trying to build this sample:
$ cc example.c -arch i386 -lvlc.2 -L/Applications/VLC.app/Contents/MacOS/lib/ -I/Applications/VLC.app/Contents/MacOS/include/ -o example
$ ./example
dyld: Library not loaded: @loader_path/lib/libvlc.2.dylib
Referenced f... | Check with otool -L if your programm is correctly linked with all your libs.
relink every dylib with install_name_tools
|
1,756,242 | 1,757,024 | Enumerating all IDispatch implementing objects on a machine | I'd like to enumerate all IDispatch supporting objects on a machine. At the moment I need to know what the class id or prog id is but, for inspecting my machine, I'd like to know if I can just enumerate all the objects that implement IDispatch.
Is this even possible?
Any help would be much appreciated :)
| That's a very odd request. The rub is in the "all" stipulation. Simple enumeration through the HKCR\Typelib key and LoadTypeLib() isn't enough, a COM server is not required to publish a type library. You would actually have to CoCreateInstance() the coclass and QueryInterface for IDispatch. Not only is this slow, i... |
1,756,285 | 1,756,419 | Stack Size Estimation | In multi-threaded embedded software (written in C or C++), a thread must be given enough stack space in order to allow it to complete its operations without overflowing. Correct sizing of the stack is critical in some real-time embedded environments, because (at least in some systems I've worked with), the operating s... | Runtime-Evaluation
An online method is to paint the complete stack with a certain value, like 0xAAAA (or 0xAA, whatever your width is). Then you can check how large the stack has maximally grown in the past by checking how much of the painting is left untouched.
Have a look at this link for an explanation with illustra... |
1,756,700 | 1,757,368 | Compile Qt application for Windows Mobile 5 | I'm trying to compile a small Qt application for windows Mobile 5.
so I've few questions:
currently i'm using ubuntu 9.10, I've hear some thing about cross-compilation but I din't found a real example of have to do it. Will it be possible to compile from linux?
How to compile an application for mobile anywhere(windows... | In order to compile applications for Windows Mobile 5 you will need either:
at least Visual Studio 2005 Standard or Visual Studio 2008 Professional (Microsoft has moved Windows Mobile support in the Professional Version).
Note: You cannot use the Express versions of Visual Studio to create applications for Windows Mo... |
1,756,867 | 1,756,903 | Qt moc_ include file problem | I'm trying to compile the basic tutorial program at http://doc.trolltech.com/4.4/mainwindows-application.html and running into a problem.
Doing things the way the tutorial program does them, gives a compile error:
In file included from debug\moc_mainwindow.cpp:10:
debug\../mainwindow.h:2: error: expected class-name bef... | Your header file has to know about Qt stuff. So there is no way to avoid including QtGui.
Edit: You shouldn't worry too much about compilation time. The inclusions will happen anyways. Maybe you can split your header into none Qt-related parts if it really gets annoying.
|
1,757,093 | 1,757,806 | Obtain the true name of the currently select file in the common file dialog? | One can get the text of the selected item in the list-view of a common dialog. But one can NOT get its PIDL, and if the user has chosen to hide known extensions (the default), then one cannot really tell what file was selected without either its extension or its PIDL.
So possible ways to solve this might be:
Obtain... | Send WM_USER+7 to get the browser, and then get its active shell view's IShellView interface.
You know the usual consequence of using undocumented behavior right?
|
1,757,110 | 1,758,163 | How could running code in the debugger makes it faster? | It never happened to me. In Visual Studio, I have a part of code that is executed 300 times, I time it every iteration with the performance counter, and then average it.
If I'm running the code in the debugger I get an average of 1.01 ms if I run it without the debugger I get 1.8 ms.
I closed all other apps, I rebooted... | I think I figured it out.
If I add a Sleep(3000) before running the tests, they give the same result.
I think it has something to do with the loading of misc. dlls. In the debugger, the dlls were loaded before any code was executed. Outside the debugger, the dlls were loaded on demand, and one or more were loaded afte... |
1,757,159 | 1,757,191 | the compiler doesn't seem to accept Agent class | probably the answer is quite silly but I need a pair fresh of eyes to spot the problem, if you will. this is the excerpt from _tmain:
Agent theAgent(void);
int m = theAgent.loadSAG();
and this is agent.h, which I included in _tmain:
#ifndef AGENT_H
#define AGENT_H
class Agent {
public:
Agent(void);
int loadSAG(void);
... | Agent theAgent(void);
This is a function declaration, just change it to:
Agent theAgent;
|
1,757,448 | 1,757,482 | How do I properly return a char * from an Unmanaged DLL to C#? | Function signature:
char * errMessage(int err);
My code:
[DllImport("api.dll")]
internal static extern char[] errMessage(int err);
...
char[] message = errMessage(err);
This returns an error:
Cannot marshal 'return value': Invalid managed/unmanaged type combination.
What am I doing wrong? Thanks for any ... | try this:
[DllImport("api.dll")]
[return : MarshalAs(UnmanagedType.LPStr)]
internal static extern string errMessage(int err);
...
string message = errMessage(err);
I believe C# is smart enough to handle the pointer and return you a string.
Edit: Added the MarshalAs attribute
|
1,757,785 | 1,759,052 | Problem statically linking MFC libraries | I have a Visual Studio 6 workspace I'm trying to convert to a Visual Studio 2008 solution. The output of said solution is a .dll. It has to be a .dll and it needs to statically link MFC as I can't redistribute MFC to existing customers.
The solution consists of three projects, say A, B, C. C is the Active Project, ou... | As is often the case, the solution turned out to be so mundane and obvious, I'm still kicking myself for banging my head on it for so long.
Basically, project A referenced above was not a project I directly pulled from the old VS6 workspace, but rather a project that had previously been converted by another team for us... |
1,757,791 | 1,757,845 | C++ template partial specialization - specializing one member function only | Bumped into another templates problem:
The problem: I want to partially specialize a container-class (foo) for the case that the objects are pointers, and i want to specialize only the delete-method. Should look like this:
The lib code
template <typename T>
class foo
{
public:
void addSome (T o) { printf ("addin... | Second solution (correct one)
template <typename T>
class foo
{
public:
void addSome (T o) { printf ("adding that object..."); }
void deleteSome(T o) { deleteSomeHelper<T>()(o); }
protected:
template<typename TX>
struct deleteSomeHelper { void operator()(TX& o) { printf ("deleting that object...");... |
1,757,942 | 1,760,924 | Interlocked and Memory Barriers | I have a question about the following code sample (m_value isn't volatile, and every thread runs on a separate processor)
void Foo() // executed by thread #1, BEFORE Bar() is executed
{
Interlocked.Exchange(ref m_value, 1);
}
bool Bar() // executed by thread #2, AFTER Foo() is executed
{
return m_value == 1;
}
... | The usual pattern for memory barrier usage matches what you would put in the implementation of a critical section, but split into pairs for the producer and consumer. As an example your critical section implementation would typically be of the form:
while (!pShared->lock.testAndSet_Acquire()) ;
// (this loop should i... |
1,757,962 | 1,757,989 | C++ boost shared array swapping pointers (simple question) | I'm new to boost shared arrays.
There is existing code that declares two arrays:
boost::shared_array<unsigned char> src;
boost::shared_array<unsigned char> dest;
All I want to do is swap what each array is pointing to (src becomes dest, and dest becomes src). As I understand it, the shared_array.get() method return... | The correct way to swap two shared_arrays (or most other Boost shared pointer types) is to use the swap member function:
src.swap(dest);
This swaps the pointers and reference counts used by each of the shared_arrays:
void swap(shared_array<T> & other)
{
std::swap(px, other.px);
pn.swap(other.pn);
}
|
1,758,026 | 1,759,114 | Format the output of qDebug for QMaps | i am currently in the process of maintaining a legacy app. This has quite a few structures like:
QMap<QString, QMap<QString, QMap<QString, QMap<QString, QVariant> > > > Dep;
As interfaces are hardly used and I only need to make minor adjustments, I would like to keep the structure as it is, although some refactoring ... | This one is for n-dimensions and will use the standard qDebug output for known types:
template<class NonMap>
struct Print
{
static void print(const QString& tabs, const NonMap& value)
{
qDebug() << tabs << value;
}
};
template <class Key, class ValueType >
struct Print<class QMap<Key, ValueType> >... |
1,758,608 | 1,758,623 | Is there an Non-Short circuited logical "and" in C++? | tl;dr: Is there a non-short circuit logical AND in C++ (similar to &&)?
I've got 2 functions that I want to call, and use the return values to figure out the return value of a 3rd composite function. The issue is that I always want both functions to evaluate (as they output log information about the state of the syste... | The & operator performs logical "and" operation for bool operands and is not short circuited.
It's not a sequence point. You cannot rely on the order of evaluation of the operands. However, it's guaranteed that both operands are evaluated.
I do not recommend doing this. Using temporary variables is a better solution. D... |
1,758,664 | 1,759,089 | java.util.concurrent vs. Boost Threads library | How do the Boost Thread libraries compare against the java.util.concurrent libraries?
Performance is critical and so I would prefer to stay with C++ (although Java is a lot faster these days). Given that I have to code in C++, what libraries exist to make threading easy and less error prone.
I have heard recently that... | Boost threads are a lot easier to use than pthreads, and, in my opinion, slightly easier to use than Java threads. When a boost thread object is instantiated, it launches a new thread. The user supplies a function or function object which will run in that new thread.
It's really as simple as:
boost::thread* thr = n... |
1,758,946 | 1,759,112 | Setting static const char[] to a predefined static const char[] fails | Hey guys! When I try to do the following in a header file
static const char FOOT[] = "Foot";
static const char FEET[] = FOOT;
I get a compiler error of error: initializer fails to determine size of FEET. I was wondering what the cause of this is, and if there is a way to rectify it. Thanks!
| Even though why you get this error has been answered, there's more to the story. If you really need for FEET to be an array, then you can make it a reference instead of a pointer:
char const foot[] = "foot";
char const (&feet)[sizeof foot] = foot;
// reference to array (length 5) of constant char
// (read the declara... |
1,759,300 | 1,759,575 | When should I write the keyword 'inline' for a function/method? | When should I write the keyword inline for a function/method in C++?
After seeing some answers, some related questions:
When should I not write the keyword 'inline' for a function/method in C++?
When will the compiler not know when to make a function/method 'inline'?
Does it matter if an application is multithreaded w... | Oh man, one of my pet peeves.
inline is more like static or extern than a directive telling the compiler to inline your functions. extern, static, inline are linkage directives, used almost exclusively by the linker, not the compiler.
It is said that inline hints to the compiler that you think the function should be i... |
1,759,312 | 1,759,390 | Single file compilation and execution in Visual C++ 2008? | I am doing a tutorial on C++ (learning it). The best way to learn is by example. I have little .cpp files with not much in them. I am using the best C++ IDE (Visual C++). Is there a way where I can have a project called "Tutorial Guide" and make my .cpp and .h files, BUT when I run them, it only runs the current file. ... | You cannot do it like you seem to want, a project implies a single output executable. What you can do is create an empty solution first then for each .cpp file you create a new project (right click the solution icon in the solution explorer and select new project).
You can then right click each project and select "Set ... |
1,759,397 | 1,759,463 | the quake 2 md2 file format (theory) | i am trying to load md2 files in opengl but i noticed that most example programs just use a
precompiled list of normals. something like this.....
//table of precalculated normals
{ -0.525731f, 0.000000f, 0.850651f },
{ -0.442863f, 0.238856f, 0.864188f },
{ -0.295242f, 0.000000f, 0.955423f },
{ -0.30... | You could use a precompiled table of normals, and use a lookup table to select one that is 'good enough' for a particular case. Each triangle is on a distinct plane, and it's that plane that has a normal, not the triangle itself.
For instance, lets imagine we have a point. Expand that point into a sphere for the purpos... |
1,759,475 | 1,759,589 | gcov creates .gcov files in the current directory. Is there any way to change this? | I'm running gcov/gcc 4.1.2 on RHEL.
When I want to specify a directory for the gcov files. Any ideas on how to do this?
| Run gcov from the directory where you want its files to be created. You'll have to use the -o argument to tell it where to look for the .gcno/.gcda files. See gcov's docs for more info.
|
1,759,612 | 1,759,658 | How to set the culture info in unmanaged C++? | I got a program written in unmanaged C++, I need to get the cultural info from the system and set that info to the current execution thread in my c++ application.
Thanks.
| In unmanaged C++ on windows, what you need is the Locale. Culture is a term defined in .NET, as a replacement for that term.
There's a whole host of functions, but the one where you need to start is called SetThreadLocale.
SetThreadLocale Function (Windows) @ MSDN
Within the documentation at MSDN, it appears that there... |
1,759,613 | 1,759,666 | What C++ idioms should C++ programmers use? | What C++ idioms should C++ programmers know?
By C++ idioms, I mean design patterns or way of doing certain things that are only applicable for C++ or more applicable for C++ than most other languages.
Why one should use the idioms, and what do the idioms accomplish?
| Here is one list. If I had to pick a couple I might go with the Curiously Recurring Template Pattern or Virtual Contstructors.
|
1,759,794 | 1,759,846 | How to print pthread_t | Searched, but don't come across a satisfying answer.
I know there's no a portable way to print a pthread_t.
How do you do it in your app?
Update:
Actually I don't need pthread_t, but some small numeric id, identifying in debug message different threads.
On my system (64 bit RHEL 5.3) it's defined as unsigned long i... | This will print out a hexadecimal representation of a pthread_t, no matter what that actually is:
void fprintPt(FILE *f, pthread_t pt) {
unsigned char *ptc = (unsigned char*)(void*)(&pt);
fprintf(f, "0x");
for (size_t i=0; i<sizeof(pt); i++) {
fprintf(f, "%02x", (unsigned)(ptc[i]));
}
}
To just print a sma... |
1,759,991 | 1,760,043 | Regular expressions performance: Boost vs. Perl | I'm looking for a performance comparison between perl and boost regular expression.
I need to design a piece of code which relies very heavily on regular expressions, and can choose between:
running it through a boost regex
dispatching a perl interpreter and do the work in perl
I know perl is known for it's opt... | The startup cost of running a Perl interpreter from within your application (via the system function I presume) will outweigh any benefits you gain over using Perl's regex engine. The exception would be if you have a VERY complicated regular expression that Perl's regex implementation happens to be optimised for but b... |
1,760,083 | 1,760,320 | How to resolve this Shift/Reduce conflict in YACC | I have a grammar like this:
"Match one or more rule1 where rule1 is one or more rule2, where rule2 is one or more rule3, etc. etc. each seperated by newlines". Look at the following example.
start: rule1_list
;
rule1_list: rule1
| rule1_list NEWLINE rule1
;
rule1: rule2
| ru... | Ambiguous grammar, not LALR(1), unparsable by default yacc mode
To make a long story short, you can "fix" this with a %glr-parser declaration as follows:
%glr-parser
%%
start: rule1_list
. . .
. . .
To make a long story kind of medium-length...
Shift-reduce conflicts are normally not errors. The conflict is resolved ... |
1,760,291 | 1,760,497 | Is compiler allowed to ignore inline in case of template specialization? | Lets say you have simple template function (not class member for the sake of simplicity) with type specific specialization in the same .h file...
template <class TYPE>
void some_function(TYPE& val)
{
// some generic implementation
}
template <>
inline void some_function<int>(int& val)
{
// some int specific... | You are misunderstanding the meaning of the often-mentioned "ignore inline" possibility.
No compiler is ever allowed to ignore the inline specifier used in function declaration and the consequences this specifier has with respect to One Definition Rule (ODR).
When someone says that compiler are allowed to "ignore inli... |
1,760,365 | 1,760,403 | Possible to Use typeid to Determine Parent-Child Relationship | all the while, I am using dynamic_cast to determine Parent-Child relationship of an object.
#include <iostream>
class A {
public:
virtual ~A() {}
};
class B : public A {
};
class C : public A {
};
int main()
{
B b;
std::cout<< typeid(b).name()<< std::endl; // class B
A* a = dynamic_cast<A *>(... | I don't think you can do that in current C++ using the information in typeinfo only. I know of boost::is_base_of (Type Traits will be part of C++0x):
if ( boost::is_base_of<A, B>::value ) // true
{
std::cout << "A is a base of B";
}
|
1,760,455 | 1,876,991 | Convert latex to html in Java or C++? | There are many tools for converting latex into html. I'm looking for a Java or C++ program to do this. It will need to run on multiple operating systems. The solution will be used on academic papers, so it should ideally also be able to interpret things like bibtex.
I found htmltolatex which is a "Java program for c... | Latex2html is the way to go. You say that you don't want any dependency, but any library you'll pick will be something you'll depend on. Latex2html:
works great,
it's part of TeX
it's relatively small that you can bundle the executable with your app
it's open source (GPL), so you might also try to link it within your... |
1,760,594 | 1,760,604 | Abstract Base Class with Data Members | If I'm creating an abstract base class, and the classes derived from it are going to have some of the same data members, is it better practice to make those members private in the abstract base class and give protected access to them? Or to not bother and just put the data members in the derived classes. This is in C++... | If the data belongs to the derived class, let the derived class do what it wants to contain that data.
By placing that data in the base class (not privately), you force every derived class to have it. The derived classes shouldn't be forced to do anything unless they need to fill out the data member, for example. The b... |
1,760,663 | 1,760,683 | What does this error message mean? | In C++, on this site: http://msdn.microsoft.com/en-au/visualc/bb985511.aspx
I downloaded the code sample and went to Debug and it came up with a messagebox with 2 textboxes in it and told me to specify the executable file to debug. So I did, and then I clicked browse, but there is NO executable because the stupid thing... | This message generally comes up when you try to debug into a system DLL or 3rd party code. Set a breakpoint with F9 and hit F5 and see if stop in your code in debug. Also make sure you are building the debug version.
happy coding.
|
1,760,726 | 1,763,484 | How can I compose output streams, so output goes multiple places at once? | I'd like to compose two (or more) streams into one. My goal is that any output directed to cout, cerr, and clog also be outputted into a file, along with the original stream. (For when things are logged to the console, for example. After closing, I'd like to still be able to go back and view the output.)
I was thinking... | You mention having not found anything in Boost.IOStreams. Did you consider tee_device?
|
1,760,957 | 1,763,123 | Binary Search Tree C++ | Im a little confused. Im wondering if an array based Binary Search tree is implemented this way?
void BST::insert(item &items, const data & aData )
{//helper function.
Parent++;
data *new_data = new data(aData);
this->insert(*new_data);
}
// insert a new item into the BST
void BST::insert(const data &aData... | I'm not sure a binary tree based on an array is the best idea, as it:
prevents node-balancing (optimizing lookups for unbalanced trees)
wastes space - tons of it, especially if the tree is unbalanced.
Having said that, it is a valid approach, with a minor change:
Change
if ( Parent >= maxSize ) this->reallocate();
t... |
1,761,047 | 1,761,083 | C++, Can't use an array or vectors, how do I use a pointer to get through this mess? | I need help with pointers and memory management.
I need to store different objects, all derived from the same base class, and have been using an array to do this but it is causing a segmentation fault when the array is populated with different objects.
My program works fine when the array is full of objects of the sa... | I won't post a complete solution because you have identified the question as homework, but I hope I can help you out with the problem a little bit:
Arrays are designed to hold many objects of the same size. The problem with storing different objects in the array (even if they are derived from the same base class) is th... |
1,761,125 | 1,769,619 | GCC memory leak detection equivalent to Microsoft crtdbg.h? | After many years of working on a general-purpose C++ library using the Microsoft MSVC compiler in Visual Studio, we are now porting it to Linux/Mac OS X (pray for us). I have become accustomed and quite fond of the simple memory leak detection mechanism in MSVC:
#ifdef DEBUG
#define _CRTDBG_MAP_ALLOC
#define NE... | You should have a look at "Cross-Platform Memory Leak Detector", looks very similar to the crtdbg.h technique.
|
1,761,173 | 1,761,191 | send SIGINT to child process | I am trying to create a child process and then send SIGINT to the child without terminating the parent. I tried this:
pid=fork();
if (!pid)
{
setpgrp();
cout<<"waiting...\n";
while(1);
}
else
{
cout<<"parent";
wait(NULL);
}
but when I hit C-c both process were terminat... | You could try implementing a SIGINT signal handler which, if a child process is running, kills the child process (and if not, shuts down the application).
Alternatively, set the parent's SIGINT handler to SIG_IGN and the child's to SIG_DFL.
|
1,761,379 | 1,761,389 | Is Returning String Reference The Best Case In Below | Let say I am designing an interface, to return the name of the child class. Note that, for different instance of a child class, their name shall remain the same.
For speed and memory efficient, I would say 3rd method signature is probably the best (based on some comment from char* vs std::string in c++)
virtual const ... | It can be if you do it correctly. What you have now is undefined:
virtual const std::string& name2() const
{
return std::string("My Baby"); // constructs temporary string!
}
You're returning a reference to a temporary. For this to work, it must be an l-value. You could make it static:
virtual const std::string& na... |
1,761,626 | 1,761,646 | Weighted random numbers | I'm trying to implement a weighted random numbers. I'm currently just banging my head against the wall and cannot figure this out.
In my project (Hold'em hand-ranges, subjective all-in equity analysis), I'm using Boost's random -functions. So, let's say I want to pick a random number between 1 and 3 (so either 1, 2 or ... | There is a straightforward algorithm for picking an item at random, where items have individual weights:
1) calculate the sum of all the weights
2) pick a random number that is 0 or greater and is less than the sum of the weights
3) go through the items one at a time, subtracting their weight from your random number, u... |
1,761,806 | 1,761,881 | What’s An Algorithm or code for the obtaining ordinal position of an element in a list sorted by value in c++ | This is similar to a recent question.
I will be maintaining sorted a list of values. I will be inserting items of arbitrary value into the list. Each time I insert a value, I would like to determine its ordinal position in the list (is it 1st, 2nd, 1000th). What is the most efficient data structure and algorithm for a... | Binary tree is fine with this. Its modification is easy as well: just keep in each node the number of nodes in its subtree.
After you inserted a node, perform a search for it again by walking from root to that node. And recursively update the index:
if (traverse to left subtree)
index = index_on_previous_stage;
i... |
1,762,043 | 1,769,068 | C++ - string.compare issues when output to text file is different to console output? | I'm trying to find out if two strings I have are the same, for the purpose of unit testing. The first is a predefined string, hard-coded into the program. The second is a read in from a text file with an ifstream using std::getline(), and then taken as a substring. Both values are stored as C++ strings.
When I output b... | It turns out that the problem was that the file encoding of myInput was UTF-16, whereas the comparison string was UTF-8. The way to convert them with the OS limitations I had for this project (Linux, C/C++ code), was to use the iconv() functions. To keep the compatibility of the C++ strings I'd been using, I ended up s... |
1,762,088 | 1,762,110 | Common reasons for bugs in release version not present in debug mode | What are the typical reasons for bugs and abnormal program behavior that manifest themselves only in release compilation mode but which do not occur when in debug mode?
| Many times, in debug mode in C++ all variables are null initialized, whereas the same does not happen in release mode unless explicitly stated.
Check for any debug macros and uninitialized variables
Does your program uses threading, then optimization can also cause some issues in release mode.
Also check for all except... |
1,762,206 | 1,762,559 | Anchor buttons in a dialog when using SW_MAXIMIZE | This should be a simple one:
I have a CDialog with 2 buttons.
The dialog is always opened in full screen (No title bar \ Status, etc...) using m_pMainWnd->ShowWindow(SW_MAXIMIZE);
I want my buttons to snap to the edge of the screen.
There are no resizing or anything.
| You know the width of the dialog (GetClientRect). You know the width of the buttons.
Assuming you are snapping to the right edge ...
Inside your CDialog::OnSize:
// Grab the CDialog's rect.
CRect winRect;
GetClientRect( &winRect );
// Grab the button's rect.
CRect buttonRect;
button.GetClientRect( &buttonRect... |
1,762,363 | 1,762,440 | Line segment in a triangle | How can we check if a line segment falls partially or fully inside a triangle?
Cheers.
| Get the function for the line from the end points of the line segment. Check where this line crosses any of the sides of the triangle.
If any part of the line segment is inside the triangle, the line will either pass in through one side and out through another, or it will pass exactly along one side of the triangle and... |
1,762,386 | 1,762,431 | Is this proper use of dynamic_cast? | I have three classes: Generic, CFG, and Evaluator.
Here's Generic:
class Generic: public virtual Evaluator, public CFG, public LCDInterface {
Here's CFG:
class CFG : public virtual Evaluator {
And Evaluator subclasses nothing.
I'm providing a DLL named PluginLCD, and it has a method called Connect:
void PluginLCD::Co... | dynamic_cast is known to break across module boundaries with many compilers (including MSVC and gcc). I don't know exactly why that is, but googling for it yields many hits. I'd recommend trying to get rid of the dynamic_cast in the first place instead of trying to find out why it returns null in your second scenario.
|
1,762,390 | 1,762,515 | How to explain C++ templates to junior developers? | One could break the question into two: how to read and to write templated code.
It is very easy to say, "it you want an array of doubles, write std::vector<double>", but it won't teach them how the templates work.
| I'd probably try to demonstrate the power of templates, by demonstrating the annoyance of not using them.
A good demonstration would be to write something simple like a stack of doubles (hand-written, not STL), with methods push, pop, and foldTopTwo, which pops off and adds together the top two values in the stack, and... |
1,762,535 | 1,762,587 | terminate called after throwing an instance of 'Poco::SystemException' | Sometimes (about 1 out of 100 runs), my program terminates with this message:
terminate called after throwing an instance of 'Poco::SystemException'
what(): System exception
my code is not the one catching the exception (all my catches are more verbose), and I am not sure where it's caught.
it's very likely that th... |
anyone knows in what code this uncaught exception is caught?
An uncaught exception is—by definition—not caught anywhere.
If an exception cannot be handled, the C++ exception mechanism will call std::terminate() (see include header <exception>), which will call a customizable termination handler. On your platform, the... |
1,762,666 | 1,762,741 | pass a string from managed C# to managed C++ | what is the preferred method to pass a string between C++ and C#?
i have a c++ class where one of the functions takes a char const * const as parameter.
how would i call this function in C#? just using a c#-string doesnt seem to work as the function in C# requires a sbyte*
C++ class:
public ref class MyClass
{
public:
... | If you are using managed C++, you can use System.String class
|
1,762,933 | 1,762,972 | Loop through MFC Child Dialogs, MDIFrames etc | Is there a way to loop through all MFC Child Dialogs, MDI frames and etc? And is there a way to find out which dialog or window I am looping through?
| You could use EnumChildWindows to iterate through child windows of certain window.
|
1,762,941 | 1,763,028 | c++ Mysql C API Connection Question | I'm building an application which uses Mysql, I was wondering what would be the best way to manage the connection to the actual Mysql server?
I'm still in the design phase, but currently I have it Connecting (or aborting if error) before every query and disconnecting after which is just for testing as right now I'm onl... | Connecting once and performing many queries will naturally be more efficient.
However, if performance isn't a major concern for your project, maybe aiming for simplicity in your code might be a better option (especially if you are the only connection to the database).
If you want to get clever, then maybe connect as an... |
1,763,082 | 1,763,171 | Recovering from stack overflow on Mac OS X | I am implementing a cross platform scripting language for our product. There is a requirement to detect and properly handle stack overflow condition in language VM. Before you jump in and say make sure there is no stack overflow in the first place, re-read my first sentence - this is a scripting language and end users ... | OCaml has the same constraints as you ("scripting" language where the programmer may cause a stack overflow). Its native compiler uses the system stack for function calls -- as you do -- and it handles stack overflows (materializing them as exceptions).
If you do not receive a more explicit answer, I suggest you look a... |
1,763,135 | 1,763,295 | C# DllImport MFC Extension DLL & Name Mangling | I have a MFC extension DLL which I want to use in a C# application. The functions I'm exposing are C functions, i.e. I'm exporting them like this
extern "C"
{
__declspec(dllexport) bool Initialize();
}
The functions internally uses MFC classes, so what do I have to do to use the DLL in C# using P/Invoke.
Secondly, I ... | Having this declaration in the header:
__declspec(dllexport) int fnunmanaged(void);
__declspec(dllexport) int fnunmanaged(int);
You could use dumpbin.exe to get the exact name of the function:
dumpbin.exe /exports unmanaged.dll
Microsoft (R) COFF/PE Dumper Version 9.00.30729.01
Copyright (C) Microsoft Corporation. A... |
1,763,166 | 1,763,315 | How to efficiently generate random subsets of rows from a matrix | I have a large matrix M implemented as vector<vector<double> with m rows, i.e. the matrix is a vector of m vectors of n column elements.
I have to create two subsets of the rows of this matrix, i.e. A holds k rows, and B the other m-k rows. The rows must be selected at random.
I do not want to use any libraries other ... | If you don't need B to be in random order, then random_shuffle does more work than you need.
If by "STL" you mean SGI's STL, then use random_sample.
If by "STL" you mean the C++ standard libraries, then you don't have random_sample. You might want to copy the implementation, except stop after the first n steps. This wi... |
1,763,322 | 1,764,960 | Is there any way that Enter/LeaveCriticalSection could leave a handle behind | I have the following code in my program:
EnterCriticalSection(&critsec[x]);
// stuff
LeaveCriticalSection(&critsec[x]);
It works fine 99.999% of the time but occasionally a handle seems to get left behind. Now I have done the obvious things like make sure that x did not change value between the enter and make su... | If you don't explicitly delete the critical section and if there was ever contention on the critical section, you will leak a handle. Some implementations of critical sections on Windows allocate a semaphore when two or more threads overlap in their attempts to enter a single critical section.
It's not a leak. Or rathe... |
1,763,368 | 1,763,424 | Is it possible to debug core dumps when using Java JNI? | My application is mostly Java but, for certain calculations, uses a C++ library. Our environment is Java 1.6 running on RedHat 3 (soon to be RedHat 5).
My problem is that the C++ library is not thread-safe. To work around this, we run multiple, single-threaded "worker" processes and give them work to do from a central ... | Yes, there is. Everytime JVM crashes because of a SIGSEGV in the JNI part, you'll get a file with core dump in $JAVA_HOME/bin directory. It usually name hs_err_PID.log.
You can get more info here, and here. Here is a somewhat related stackoverflow question.
|
1,763,739 | 1,763,874 | Problem retuning a vector from a c++ dll to another c++ exe | I have a function foo() in dll A.dll, whose definition is as follows
vector<CustomObject> foo()
{
vector<CustomObject> customObjectCollection;
//code which populates customObjectCollection goes here
return customObjectCollection;
}
I am referring this method vector foo() of dll A from exe B
When i ... | This is a classic symptom of mismatched runtime libraries. You have to make sure that both the EXE and the DLL are linked to the dynamic C++ library (DLL version).
If one (or both) are linked with the static C++ runtime (LIB version), you'll get memory violations since there will be two instances of the runtime library... |
1,764,079 | 1,764,086 | Why do you prefer char* instead of string, in C++? | I'm a C programmer trying to write c++ code. I heard string in C++ was better than char* in terms of security, performance, etc, however sometimes it seems that char* is a better choice. Someone suggested that programmers should not use char* in C++ because we could do all things that char* could do with string, and it... | It's safer to use std::string because you don't need to worry about allocating / deallocating memory for the string. The C++ std::string class is likely to use a char* array internally. However, the class will manage the allocation, reallocation, and deallocation of the internal array for you. This removes all the u... |
1,764,082 | 1,764,754 | boost filtering_istream gzip_decompressor uncompressed file size | I am using the boost filtering stream object to read gzipped files. Works great!
I would like to display a progress bar for the amount of the file that has been processed. I need find the input uncompressed file size. Does the gzip decompressor have access to the original file size from the gzipped file? I couldn't... | The information you are after is definitely there (uncompressed data size is recorded into the last 4 bytes of a gzip file, (see GZIP spec) but taking a look at the headers for the boost library (seen here) it is not exposed anywhere. The only place it seems to be even looked at is when doing checks to make sure there... |
1,764,179 | 1,764,237 | Passing around base class pointers | Scenario: I have the following defined classes.
class Baseclass { };
class DerivedTypeA : public Baseclass { };
class DerivedTypeB : public Baseclass { };
// ... and so on ...
class Container
{
list<Baseclass*> stuff;
list<DerivedTypeA*> specific_stuff;
// ... initializing constructors and so on ...
public:
... | Overload resolution in C++ happens at compile-time, not run-time. The "usual" way to solve problems like this is to use Visitor pattern.
You can reduce the amount of boilerplate copy-paste by implementing Visitor with CRTP.
If you use CRTP for Base::accept, you don't need to define it any more in derived classes.
Here ... |
1,764,239 | 1,764,270 | Class composed of other, larger, classes problem | Imagine you have a class with dozens of private member variables. Each member variable has a public getter and a setter function:
class Foo
{
public:
int GetA() const { return m_a; }
:
int GetZ() const { return m_z; }
void SetA(int val) { m_a = val; }
:
void SetZ(int val) { m_z = val; }
pr... | You should make the data member public.
It already is conceptually public, anyway, if you give Bar getters and setters like you describe. This applies similarly to any getter/setter pair where the getter returns a reference. (Except you can include pre/post hooks, but that's a separate issue than encapsulation.)
|
1,764,624 | 1,764,760 | C++ singleton design: using inheritance to call only some implemented methods | I have a singleton that is the main engine container for my game.
I have several abstract classes that make the developer implement the different calls to what that specific object needs.
What I want to do is to make my singleton call those methods upon each given object, but avoiding unecessary calls.
Example so you c... | If you don't need to call the chain CheckInput(), Update(), .... on each object before moving on to the next one, make a call to to the object, and make the object register which actions it supports on the singleton.
class Singleton {
void Add(Base& object) {
object.register(this);
}
void registerForInput(II... |
1,764,665 | 1,764,714 | .Net performance on Virtual Machines | We need to develop an application which is going to be installed on Virtual Machine running Windows.
We all know the performance of the .Net is about the same as the native C/C++ code. Is it also true for Virtual Machines?
| .net apps running on a VM compared to non .net apps running on the same VM will perform equivalently to comparing .net and non .net apps running on a real machine.
What I'm trying to say is that .net apps are no more or less disadvantages than native apps by running them on a VM. If you have 2 apps (one .net and one na... |
1,764,680 | 1,764,766 | Can I extract C++ template arguments out of a template class? | Basically, given a template class like this:
template< class Value > class Holder { };
I would like to be able to discover the type Value for a given Holder class. I thought that I would be able to make a simple metafunction that takes a template template argument, like this:
template< template< class Value > class ... | Why don't you simply change your holder class to
template< class Value > class Holder {
typedef Value value_type;
value_type m_val; // member variable
};
In any method that consumes an object of type Holder< T > you can access the contained type like that:
template< class THolder >
void SomeMethod( THolder co... |
1,764,831 | 1,764,851 | C++ Object without new | this is a really simple question but I havn't done c++ properly for years and so I'm a little baffled by this. Also, it's not the easiest thing (for me at least) to look up on the internet, not for trying.
Why doesn't this use the new keyword and how does it work?
Basically, what's going on here?
CPlayer newPlayer = C... | This expression:
CPlayer(position, attacker)
creates a temporary object of type CPlayer using the above constructor, then:
CPlayer newPlayer =...;
The mentioned temporary object gets copied using the copy constructor to newPlayer. A better way is to write the following to avoid temporaries:
CPlayer newPlayer(position... |
1,764,920 | 1,764,976 | std::ostream not formatting const char* correctly the first time it's used | I've been writing a custom std::streambuf as part of a logging system. However, I'm having problems with the first piece of output from a stream not being formatted correctly.
Here's a reduced test-case that doesn't use any custom streambuf or ostream classes:
#include <iostream>
int main()
{
std::streambuf *coutb... | The problem is that you must not write to a temporary stream object. This:
std::ostream(coutbuf) << "blah";
doesn't work as expected, since the left-hand argument for operator<<() is an rvalue. However, all the operators overloaded as a free function take a non-const reference to a stream as their left-hand argument:... |
1,764,980 | 1,765,125 | 'Safe' DLL Injection | Not a terribly good question, sorry.
I have a program that needs to be alerted when a file is opened from explorer (i.e. ShellExecute(A/W) is called).
Unfortunately, Microsoft removed the COM interface (IShellExecuteHook) that allows you to hook these events in Vista and up, supposedly because older code could cause a ... | Most good antivirus heuristics should pick up on import table patching as being a red flag for a trojan.
The online documentation for madcodehook has some extended articles on various code injection techniques, their benefits/drawbacks, and the API provides some options for specifying "safe" hooking:
http://www.madshi... |
1,765,014 | 1,765,088 | Convert string from __DATE__ into a time_t | I'm trying to convert the string produced from the __DATE__ macro into a time_t. I don't need a full-blown date/time parser, something that only handles the format of the __DATE__ macro would be great.
A preprocessor method would be nifty, but a function would work just as well. If it's relevant, I'm using MSVC.
| Edit: the corrected function should look something like this:
time_t cvt_TIME(char const *time) {
char s_month[5];
int month, day, year;
struct tm t = {0};
static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
sscanf(time, "%s %d %d", s_month, &day, &year);
month = (strstr... |
1,765,119 | 1,765,200 | What Is a Good Introduction and Tutorial on Internationalization and Localization? | My company uses an internally developed package to support internationalization/localization. However, it was developed some twenty years ago, and the libraries are restricted to one product line. I'm interested in where the state of the art stands. Is Unicode the base character set for all international efforts today?... | This article seems quite interesting and provides you with some interesting bibliography in the end.
Also, you may want to take a look at the ICU Project's website.
|
1,765,122 | 1,765,187 | Equality Test for Derived Classes in C++ |
Possible Duplicate:
What’s the right way to overload operator== for a class hierarchy?
In C++, how can derived classes override the base class equality test in a meaningful way?
For example, say I have a base class A. Classes B and C derive from A. Now given two pointers to two A objects, can I test if they are equa... | I remember reading a succinct description of the public-non-virtual/non-public-virtual idiom and its advantages, but not where. This wikibook has an okay description.
Here is how you apply it to op==:
struct A {
virtual ~A() {}
int a;
friend
bool operator==(A const& lhs, A const& rhs) {
return lhs.equal_... |
1,765,301 | 1,766,035 | fcntl() for thread or process synchronization? | Is it possible to use fcntl() system call on a file to achieve thread/process synchronization (instead of semaphoress)?
| Yes. Unix fcntl locks (and filesystem resources in general) are system-wide, so any two threads of execution (be they separate processes or not) can use them. Whether that's a good idea or not is context-dependent.
|
1,765,310 | 1,765,604 | What are the limitations of C++ running on the iPhone? | I like C++ a lot and to be honest the Objective-C "super set" of C is more of a "super fail". Can an iPhone application be written in pure C++? Are there parts of the API that are unavailable from C++?
| You can't code purely in C++. For one, the UIApplicationDelegate class every application needs to inherit is Objective-C.
However, nothing is stopping you from coding everything that isn't framework related in Objective-C++. You'll still need to use the Objective-C calls for UIKit and other frameworks, but all of your ... |
1,765,431 | 1,765,489 | C++ Comparing Member Function Pointers | In C++, is it possible to define a sort order for pointers to member functions? It seems that the operator< is undefined. Also, it's illegal to cast to void*.
class A
{
public:
void Test1(){}
void Test2(){}
};
int main()
{
void (A::* const one)() = &A::Test1;
void (A::* const two)() = &... | Function pointers are not relationally comparable in C++. Equality comparisons are supported, except for situations when at least one of the pointers actually points to a virtual member function (in which case the result is unspecified).
Of course, you can always introduce an ordering by implementing a comparison predi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.