question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,470,215 | 3,470,231 | What is the preferred way of passing data between two applications on the same system? | I have an application (A) that needs to launch another application (B). I need to pass data between the applications. I can think of two approaches. The first is to open a socket. The second is to share data via a dll.
The opening socket approach is straight forward.
The dll approach I have some questions? I c... | You can't effectively share data via a DLL. Other ways:
disk files
pipes
shared memory
messages
RPC
CORBA
COM
etc.
|
3,470,328 | 3,470,454 | OpenGL: Crashes at random OpenGL function call | I am getting weird problem, the crash happens at random times, for example i managed to use the 3d app for a while without crashing, then most of the times it crashes always when i suddenly render a lot of objects at same time.
I have recently noticed that changing the huge texture surface on this ATI card will crash ... | IMO, chances are pretty good that the crash in OpenGL is only a symptom, and the real problem lies elsewhere. In general, your description sounds more or less typical for resource misuse (e.g., memory leakage, using a dangling pointer, trashing the heap, etc.)
Something like a driver bug is certainly possible -- in fac... |
3,470,476 | 3,470,582 | XML search algorithm C++ | I am trying to find out how to write XML search algorithm.
Following is the my File
<DUMMYROOT>
<root>Job Started</root>
<root>Job Running</root>
</DUMMYROOT>
and I want search string as <root>Job Started</root>
I should be able to supply inner level of nodes as a search string like
<DUMMYROOT><root1><root2><root3... | Here's something I wrote a few years ago that seems to fit reasonably well with what you're looking for (though make no mistake, it is kind of ugly, and if the XML is really badly formed, it might run into a problem).
template <class OutIt>
void split(string const &input, string const &sep, OutIt output) {
size_t s... |
3,470,668 | 3,473,287 | Copy or reference semantics of boost::spirit's rule<>? | I am trying to write a shell language parser in Boost.Spirit. However, I am unclear about some basic issues regarding semantics of rules.
Looking at the documentation, there are members r.alias() and r.copy() of rule. IIUC, these members should return a reference to the rule and a copy of the rule's contents, respectiv... | The answer depends on what version of Spirit you're referring to.
Spirit.Classic (the former Spirit V1.x) implements special copy semantics for rules. The documentation says:
When a rule is referenced anywhere in
the right hand side of an EBNF
expression, the rule is held by the
expression by reference. It is ... |
3,470,704 | 3,470,901 | Setting GDB hardware watchpoint/how to set software watchpoint | An earlier question explained that on x86 the size of objects being watched is limited by debug registers. As expected, I can "watch" a double variable. But I can't watch a double datamember, for example,
watch pObject->dPrice
produces
Hardware watchpoint 1: pObject->dPrice
But when you try to continue execution, it ... | Yes, you can:
set can-use-hw-watchpoints 0
From 5.1.2 Setting Watchpoints:
You can force GDB to use only software watchpoints with the set can-use-hw-watchpoints 0 command. With this variable set to zero, GDB will never try to use hardware watchpoints, even if the underlying system supports them. (Note that hardware... |
3,470,935 | 3,471,026 | how to read absolute positions of tap from Cirque touchpad in linux | we have one of Cirque touchpads.
http://www.cirque.com/downloads/docs/tsm9925.pdf
now we want to read absolute position of tap from this touchpad using c\c++ application. unfortunately company developed only windows drivers but we need to read positions in the linux. we tried to use /dev/input/eventN subsystem but rec... | From your supplied link:
For custom functionality at the product design stage, we offer software that
allows OEMs to enable, disable or personalize advanced settings and/or
reprogram the touch sensitive area.
I'd suggest contacting Cirque directly
|
3,471,045 | 3,471,115 | Debug this c++ program | I need help to debug this program .
// VirtualFN.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <iomanip>
using namespace std;
enum isautostart { no,yes };
class vehicle {
protected:
static int noofvehicles;
... | The problem is probably here:
char bools;
cout <<"Vehicle has autostart function ? : (y/n)"; cin >> bools;
if(bools == 'y'){
autostart = yes;
}
else { autostart = no; }
To get this to work you need to type "Y<Enter>" to make the buffer flush.
But the code only reads the "Y" from the input s... |
3,471,148 | 3,471,322 | Pthreads- 1 lock, 2 unlocks | If I understand correctly, then foo1() fails to unlock &private_value_. As a result, foo2()'s thread_mutex_lock does not work since foo1() never released it.
What are the other consequences?
int main ( ... )
foo1();
foo2();
return 0;
}
foo1()
{
pthread_mutex_lock(&private_value_);
do something
// no unlock!
}
f... | There seems to be some confusion here between how the program should have been written and how the program, as currently written, will behave.
This code will cause deadlock, and this does not indicate that there is something wrong with how the mutexes are working. They're working exactly how they are supposed to: If y... |
3,471,284 | 3,471,528 | boost bind template error | //error C2784: 'HRESULT get_wrapper(T *,boost::function<R(void)>)' :
//could not deduce template argument for 'boost::function<R(void)>'
//from 'boost::_bi::bind_t<R,F,L>'
STDMETHODIMP CAttributeValue::get_Name(BSTR* pVal)
{
return get_wrapper(pVal, boost::bind<BSTR>(&CAttributeValue::getNameCOM, this)); //error... | Does it help to do this?
return get_wrapper<BSTR>(pVal, boost::bind(&CAttributeValue::getNameCOM, this));
// ^^^^^^
There is a conversion from the type returned by boost::bind to boost::function<T()>, but since this parameter depends on a template argument, the compiler won't do any such conversions on ... |
3,471,314 | 3,471,492 | Unsafe to throw exceptions from statically linked C++ libraries? | I've heard that throwing exceptions in/from a C++ library could be potentially dangerous, particularly with DLLs, and particularly if the calling code and the library are compiled with different compilers. Is there any truth to this? Is it safe as long as I stick to static libraries? Note that I am not talking about in... |
and particularly if the calling code and the library are compiled with different compilers
You generally can't mix different C++ compilers that do not have compatible ABI. So, for example, you can't throw exception from library compiled with MSVC and try to catch
it with GCC.
But otherwise, you generally have no issu... |
3,471,399 | 3,471,434 | getting rat out of a maze | A rat is placed in a maze at some unknown position in the maze.
All we can go is in up, down, right or left directions. And we have two methods:
tryMove(<direction>) which returns false if there is a wall and true if we can move.
bool hasLadder(): which returns true if there is a ladder to escape.
We have to write ... | Both breadth-first and depth first search require memory and a naive algorithm can loop indefinitely. A rat probably only has O(1) memory.
One way to solve it without remembering where you have been is to pick a direction at random. The solve time will be extremely long, but it should eventually reach every reachable s... |
3,471,466 | 3,471,489 | Declaring a const BYTE * in c++ | I am currently trying to make a call to this function call. Here's the declaration:
const void* WINAPI CertCreateContext(
__in DWORD dwContextType,
__in DWORD dwEncodingType,
__in const BYTE *pbEncoded,
__in DWORD cbEncoded,
__in DWORD dwFlags,
__in_opt PCERT_CREATE_CONTEXT_PARA pC... | You don't need to. The function parameter is a pointer to a const BYTE, which means the function will not change the byte it points to. A simple example:
void f( const BYTE * p ) {
// stuff
}
BYTE b = 42;
BYTE a[] = { 1, 2, 3 };
f( & b );
f( a );
You will of course need to #include the header that declares the... |
3,471,520 | 3,471,587 | How to remove scrollbars in console windows C++ | I have been checking out some Rogue like games (Larn, Rogue, etc) that are written in C and C++, and I have noticed that they do not have the scrollbars to the right of the console window.
How can I accomplish this same feature?
| To remove the scrollbar, simply set the screen buffer height to be the same size as the height of the window:
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
// get handle to the console window
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
// retrieve screen buf... |
3,471,917 | 3,473,311 | How to strip HTML from a text property of a Qt4 widget? | What's the easiest way in terms of coding effort, to change a text property of a Qt4 widget, e.g. QLabel.text, so all HTML tags are removed?
The HTML is simple, typically just one to three tags like or and their closing partners.
| I've used this in the past, although the widget seems like overkill. QtextEdit, the rich text edit block. What makes this work is that the constructor assumes that the string has tags.
QTextEdit htmlText(HtmlText); // HtmlText is any QString with html tags.
QString plainText = htmlTextEdit.toPlainText();
|
3,471,968 | 3,472,106 | Adding class functionality via composition | Suppose we have an abstract class Element from which classes Triangle and Quadrilateral are derived from.
Suppose yet that these classes are used in conjunction with interpolation methods that depend on the shape of the element. So, basically we create an abstract class InterpolationElement from which we derive Interp... | The classes are used in conjunction with interpolation methods. Why do those methods need to be in a singleton object? The singleton here looks very problematic.
class Element
{
public:
virtual double interpolationMethod1(...) = 0;
:
virtual double interpolationMethodN(...) = 0;
};
class Tri... |
3,471,997 | 3,472,596 | Private class functions vs Functions in unnamed namespace | I've found myself that I tend not to have private class functions. If possible, all candidates to private class function rather I put in to unnamed namespace and pass all necessary information as function parameters. I don't have a sound explanation why I'm doing that but at least it looks more naturally to me. As a co... | In the semi large projects where I usually work (more than 2 million lines of code) I would ban private class functions if I could. The reason being that a private class function is private but yet it's visible in the header file. This means if I change the signature (or the comment) in anyway I'm rewarded sometimes wi... |
3,472,099 | 3,472,163 | Why does libxml2 output "text" on an element name (when it's not "text")? | I am use libxml2 for XML parsing. The sample code on the libxml website are hard to follow and seem to lack some details. I arrived at the following code by Googling so I don't even think it's the proper way to do it, but it worked in the sample learning program I wrote, but not this one. I still don't know the proper ... | The problem is that you are not advancing the current node in your while loop. Try changing cur->next; to cur = cur->next;. You are seeing the first child of <netlist> which is a text node containing the whitespace before the <parts> element.
|
3,472,295 | 3,473,784 | Use template template class argument as parameter | Modern C++ Design gives the following example:
template <class T> struct EnsureNotNull
{
static void Check(T*& ptr)
{
if (!ptr) ptr = GetDefaultValue();
}
};
template
<
class T,
template <class> class CheckingPolicy = EnsureNotNull,
template <class> class ThreadingModel
>
class SmartPtr
: ... | You are trying to pass SmartPtr as a template type argument to ThreadingModel. SmartPtr however is a template, not a concrete type, and the injected class-name is not available in the inheritance list.
Also note that you can't just use default arguments for template parameters in arbitrary positions (§14.1/11):
If ... |
3,472,342 | 3,472,360 | Indirectly destroying object from it's own virtual method. Is it a defined behavior? | Am I allowed to indirectly destroy object from within object's own virtual method?
Is it a "defined behavior" (as long as I'm not trying to access anything after destroying the object)?
Example:
#include <memory>
#include <stdio.h>
using std::tr1::shared_ptr;
struct Child{
virtual void selfdestruct() = 0;
vir... | Well, a virtual method can call delete this. After the call though, NOTHING ELSE THAT TOUCHES THAT OBJECT INSTANCE can be done, or you have invoked undefined behavior. That includes calling other methods (even non virtual methods), accessing any instance variable, or the like.
Your specific code above invokes undefined... |
3,472,517 | 3,472,541 | Finding the memory address of a loaded DLL in a process in C++ | I've got a running process which is using 'Test.dll'. I would like to know the exact memory location of the start of Test.dll in memory, but can't seem to be able to.
My main problem is that I need to write to an offset from this DLL, but I can't exactly type in Test.dll+some offset when I use Read/WriteProcessMemory.
... | Okay, so one way to do it is to use the value returned by GetModuleHandle(). Yes, it returns a HANDLE, but you can cast that to the appropriate pointer type. Compare to the module's address range in the Modules window of Visual Studio and you'll see it is the same as the starting value for the range.
A better way to ... |
3,472,620 | 3,472,686 | Can I use a SFINAE test in a control flow statement? | I have an SFINAE test for checking if an class has a function. The test works correctly, but I get compiler errors when I try to use it in an if statement.
//SFINAE test for setInstanceKey()
template <typename K>
class HasSetInstanceKey
{
template <typename C>
static char test( typeof(&C::setInstanceKey) );
... | Just because the if-branch is never entered doesn't mean the code within the branch can be invalid. (Another way to think about it: you aren't guaranteed anything about optimizations, yet your code would only be valid with a dead-branch optimization.)
What you do is shift the branch to a function. Typically you have a ... |
3,472,639 | 3,472,744 | How do I get the content with libxml2? | I'm using libxml2 and C++. The following function crashes here at return (char*)cur->content;. When I change it to return (char*)cur->name; then it will return attribute which is the name of the tag. What I want is 1, 2, and 3 (based on the XML file below the C++ code). What am I doing wrong?
char* xml2sdf::getId(xmlNo... | I discovered it should be return (char*)cur->children->content; by trial and error.
|
3,472,748 | 3,499,045 | How to Detect Screen Orientation Change Event in Windows Mobile 5 & 6 App, With Embedded C++? | I am in way over my head, and am hoping anyone here can help.
I am working with an application that is running on Windows Mobile OS, version 5 and/or 6, which is written in Embedded C++. The problem is that controls in the app get all messed up and moved around when the user does something to switch the display orienta... | This function should detect if the screen is in protrait mode:
BOOL IsPortrait()
{
DEVMODE devmode;
ZeroMemory(&devmode, sizeof(DEVMODE));
devmode.dmSize = sizeof(DEVMODE);
devmode.dmDisplayOrientation = DMDO_0;
devmode.dmFields = DM_DISPLAYORIENTATION;
ChangeDisplaySettingsEx(NULL, &devmode, NULL, CDS_TEST... |
3,472,913 | 3,473,012 | Is there a way to debug with the visual studio command prompt? | I've got a project that I need to get working with 3 compilers (Borland, gnu, and Microsoft). It works on 2/3 and now I just need to get it working with Microsofts. It seems to crash in places where it works fine with the other compilers, so I'm wondering if there is a way to debug with the command line, maybe to get... | (Full disclosure: I work on the Visual Studio team)
If you're using the Microsoft C++ compiler, do you have Visual Studio installed already? If so, you can use the built-in debugger. If not, I would recommend trying Visual C++ 2010 Express for free. It has an excellent native debugger. You can break on first chance... |
3,473,046 | 3,473,057 | Error - "throws different exceptions" in C++ | I am getting an error that tells me
error: declaration of 'virtual FXHost::~FXHost()' throws different exceptions
error: than previous declaration 'virtual FXHost::~FXHost() throw ()'
I am not sure how to begin solving this, I have never encountered this before.
in my .h I have:
public:
virtual ... | The throw() at the end of a function declaration is an exception specification. It means the function never throws an exception. This cannot be overridden (only restricted further) in derived classes, hence the error.
Since your implementation doesn't throw exceptions itself, all you need is adding throw() to your dest... |
3,473,152 | 3,473,157 | What is the lowest possible process ID that a Linux process can have? | On my system the lowest ID running right now is 1 (init). I'm making a small wrapper function around pidof and I was wondering, what is the lowest possible process ID a process can have?
The reason I ask is because I would like to return an integer from my function indicating "process was not running" (pidof itself ret... | PIDs are always positive, so both 0 and -1 are OK as non-PID sentinels. Several PID-related system calls, like wait() and kill(), assign special meaning to these values.
|
3,473,231 | 3,473,275 | what C++ casting operator is equivalent to (MyStructType){1,2,3}? | Is there an C++ casting operator (or combination thereof) equivalent to the old-style cast below:
struct MyStruct {
int i;
int j;
int k;
};
void do_something_with_mystruct( MyStruct ms ) {
...
};
int main( int argc, char** argv ) {
do_something_with_mystruct( (MyStruct){1,2,3} );
};
| The construct
(MyStruct) {1,2,3}
is not actually a cast! It's an ISO C99 "compound literal". There is no equivalent using any of the C++ *_cast<> operators, because C++ (even C++0x) does not include this construct. Some compilers implement it as an extension to C++, but you still have to write it this way. See for... |
3,473,264 | 3,473,321 | C++ pointer to array of pointers to function pointers? any clue how to do it? | Maybe is a silly questiion, but I haven't found a solution to what I want. Basically, I would like to declare a pointer to an array of pointers to function pointers to functions with N parameters that returns an const pointer to an int.
The code below is declaring an array of pointers to the function pointers:
int *c... | The answer is multiple levels of typedefs to make this close to understandable. If you figure this out tonight, you'll want to still be able to understand it in the morning.
typedef int *const (*myFuncPtr)(...); // pointer to function taking ... and returning constant pointer to int
typedef myFuncPtr myFuncArray[10]; ... |
3,473,298 | 3,473,310 | Program to create a hash table | I want to read an array of integers, hash each integer and put it into an hash table and later lookup the table to search for the value. What would be the efficient way to do that in c/c++? Thanks in advance
| If your compiler supports it, you can use std::unordered_set. If your compiler doesn't support that yet, most implementations support hash_set (which is well documented in the SGI STL documentation).
|
3,473,338 | 3,473,709 | OpenGL Multisampling Lines | Is there a way to just use multisampling on just lines drawn with OpenGL and not with the entire program? Thanks in advance!
| Try to enable anti-aliased lines with glEnable(GL_LINE_SMOOTH), plus you can also add a glHint(GL_LINE_SMOOTH_HINT, GL_NICEST). These might get you what you want even it's not true multisampled drawing.
|
3,473,438 | 3,473,448 | Return array in a function | I have an array int arr[5] that is passed to a function fillarr(int arr[]):
int fillarr(int arr[])
{
for(...);
return arr;
}
How can I return that array?
How will I use it, say I returned a pointer how am I going to access it?
| In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:
int fillarr(int arr[])
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
int fillar... |
3,473,511 | 3,473,549 | How can i attach userdata to each item in a listview? C++ Win32 | I was thinking i could use the LVITEM structures LPARAM to attach a pointer to my class, but i can't seem to get it to work!
Heres the main parts of my code:
Creating the listview:
hlvQuiz = CreateChild(WC_LISTVIEW, "",
WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | LVS_ICON | LVS_AUTOARRANGE,
0, 0, 320, 24... | I haven't worked at this low level before, but I suspect you need to set the mask member of the LVITEM structure to LVIF_PARAM (as well as the appropriate values for anything else you need) for the call to ListView_GetItem.
|
3,473,517 | 3,479,240 | Does the GPC polygon clipper do triangulation? | I was looking at this question Here in regards to this library. However it is still unclear to me if this library can do like glu tesselator does and return a series of triangles which I can then render with OpenGL. If it can do this, how is this done? I'm just not clear on this from reading the docs. So essentially wh... | GPC will either produce contour (polygon boundary) output, or will give a result as a series of triangle strips for the solid rendering of polygon interiors. Two functions select between the two kinds of output: gpc_polygon_clip() and gpc_tristrip_clip(). Cheers, --Toby Howard, GPC Licensing Manager.
|
3,473,771 | 3,473,858 | Crossplatform alternative to Winsock? | I basically am looking for a cross platform way to do basic things such as accept connections and send and receive data. What library would work in Linux, Windows and Mac?
Thanks
| Winsock is based on the BSD sockets API, which is natively supported on both Linux and OS X (ie. socket(), connect(), accept(), send(), recv(), select() and so forth).
There are some differences, but they are such that it's usually easier to port from Winsock to true BSD sockets than the reverse.
|
3,473,898 | 3,473,907 | Where is dynamic memory allocated? | The question was asked to me in an interview and my answer was "computer memory". But where exactly..? is it the Random Access Memory or the hard drive?
| They were probably looking for "the heap". This is an area of memory that's separate from "the stack", which is where all your local variables, parameters, return values, etc., are stored. And yes, it's all in RAM, not on the hard drive.
|
3,473,900 | 3,473,945 | The best database for a C++ and java applications | Hi I am making an ATM console application in C++. I am planning to use a database, my friend suggested to use files. However, I want to use a database like mySql, Oracle or sqlServer express.
Q: Which one of the databases would be more applicable for a C++ application ?
I am also making a second application in java. T... | Maybe you can have a look at
Comparison of relational database
management systems
Oracle and MySQL Compared
MySQL or SQL Server: Look beyond
politics and hype when deciding which
to use
and
Cross Compare of SQL Server, MySQL, and PostgreSQL
|
3,473,938 | 3,473,953 | How Can This Recursive Function Work? | I can't figure out how this works, to my mind, once it gets to the answer it doesn't do anything with it.
Node* FindNode(Node *rootNode, int data)
{
if (!rootNode)
return NULL;
else
{
if (rootNode->data == data)
return rootNode;
else
{
FindNode(rootNode->left, data);
FindNode(rootNode->ri... | It doesn't. It should be:
Node* FindNode(Node *rootNode, int data) {
if (!rootNode) {
return NULL;
}else if (rootNode->data == data) {
return rootNode;
}else if (data < rootNode->data) {
return FindNode(rootNode->left, data);
}else{
return FindNode(rootNode->right, data);... |
3,474,117 | 6,261,633 | How to convert this C++ code to Objective C | What would be equivalent Objective C for this:
template<class T>
class Singleton
{
public:
static T * instance()
{
static T t;
return &t;
}
private:
Singleton();
~Singleton();
};
While calling:
friend class Singletone<MyManagerClass>;
| #define SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)instance { ... |
3,474,119 | 3,474,215 | const type qualifier soon after the function name | In C++ sometimes I see declarations like below:
return_type function_name( datatype parameter1, datatype parameter2 ) const
{ /*................*/}
What does this const type qualifier exact do in this case?
| $9.3.1/3 states-
"A nonstatic member function may be declared const, volatile, or const volatile. These cvqualifiers affect the type of the this pointer (9.3.2). They also affect the function type (8.3.5) of the member function; a member function declared const is a const member function, a member function declared vol... |
3,474,383 | 3,474,408 | Any good C++0x overviews? | I teach C and C++ and I was just wondering if there are good overview of the C++0x features.
I am going to read the standard, but that will take time and I'm definitely going to make it for this semester (next year hopefully). For this semester I just want to make one extra lecture about C++0x (and maybe make sure that... | The best two I know of are the Wikipedia page and Stroustrup's FAQ.
I really wouldn't recommend reading the standard until you know what you're looking for. Besides being significantly larger than the C++03 standard, the organization and clarity has gotten somewhat worse in parts.
If you're only going to do one lecture... |
3,474,857 | 3,474,887 | How can I use std::binary_search using just a key? | I have some data that is stored in a sorted vector. This vector is sorted by some key. I know the STL has an algorithm for checking if an element is in this sorted list. This means I can write something like this:
struct MyData { int key; OtherData data; };
struct MyComparator
{
bool operator()( const MyData & d1, co... | Do:
struct MyComparator
{
bool operator()(int d1, const MyData & d2) const
{
return d1 < d2.key;
}
bool operator()(const MyData & d1, int d2) const
{
return d1.key < d2;
}
};
The predicate is called like pred(value, ...) or pred(..., value), so just take in the value directly. ... |
3,474,949 | 3,474,967 | Over reliance on macros | I feel, every time I read a C or C++ program, that half or more of it is just macros. I understand that macros can be cool but they are hard to track, debug, etc. Not to mention that most programming languages do not even define something like macros (although Perl6 will have something of the sort).
I personally always... | Yes, here's one. When you need to add tracing code to your program in such a way that one configuration contains it and the other completely omits you have to use macros.
Something like:
#ifdef WITH_LOGGING
#define LOG( x ) DoLog( x )
#else
#define LOG( x )
#endif
now you use it this way:
LOG( L"Calling blahbl... |
3,474,990 | 3,475,097 | Unions to extract data | Won't the union in this question cause UB when used as this:
union Data
{
unsigned int intValue;
unsigned char argbBytes[4];
};
Data data;
data.intValue = 1235347;
unsigned char alpha = data.argbBytes[0]; //UB?
I'm thinking about 9.5/1 in the standard:
In a union, at most one of the data
members can be acti... | in general you are right, writing a value of one type to a union then reading it out as a different type is undefined behaviour. on the other hand iirc the standard explicitly allows anything to castable as a char array. it's never been 100% clear to me which takes precedence, but all implementations I have ever used a... |
3,475,030 | 3,475,075 | different types of objects in the same vector array? | I am using an array in a simple logic simulator program and I want to switch to using a vector to learn it but the reference I am using "OOP in C++ by Lafore" doesn't have a lot about vectors and objects so I am kinda of lost .
Here is the previous code :
gate* G[1000];
G[0] = new ANDgate() ;
G[1] = new ORgate;
//gate ... | You're half-way there:
std::vector<gate*> G;
G.push_back(new ANDgate);
G.push_back(new ORgate);
for(unsigned i=0;i<G.size();++i)
{
G[i]->Run();
}
Of course, this way you need to take care to ensure that your objects are deleted. I'd use a vector of a smart pointer type such as boost::shared_ptr to manage that for ... |
3,475,057 | 3,475,212 | Gdb gives no stack on a simple std::string uncaught exception | im a little bit newbie on gdb so here goes:
Im working on cpp unit testing operation right now. I try to construct string objects with invalid parameters like null_char but program expectedly gives exceptions :). When i try to debug the app using gdb, i type bt after the crash, but it gives me no stack message.
Any id... | Add the -g option to your compiler command line to add debugging symbols. That helps a lot with gdb.
|
3,475,072 | 3,517,526 | Vim different textwidth for multiline C comments? | In our C++ code base we keep 99 column lines but 79-some-odd column multiline comments. Is there a good strategy to do this automagically? I assume the modes are already known because of smart comment line-joining and leading * insertion.
| Apparently both code and comments use the same textwidth option. As far as I can see, the only trick is to set this option dynamically:
:autocmd CursorMoved,CursorMovedI * :if match(getline(.), '^\s*\*') == 0 | :setlocal textwidth=79 | :else | :setlocal textwidth=99 | :endif
Here the critical part is detecting when w... |
3,475,152 | 3,475,297 | Why can't I increment a variable of an enumerated type? | I have a enumerated type StackID, and I am using the enumeration to refer to an index of a particular vector and it makes my code easier to read.
However, I now have the need to create a variable called nextAvail of type StackID. (it actually refers to a particular stackID ). I tried to increment it but in C++, the fo... |
I'm probably overlooking something obvious, but what's a good substitute?
Overloading operator++:
// Beware, brain-compiled code ahead!
StackID& operator++(StackID& stackID)
{
#if MY_ENUMS_ARE_CONTIGUOUS && I_DO_NOT_WORRY_ABOUT_OVERFLOW
return stackID = static_cast<StackID>( ++static_cast<int>(stackID) );
#else
... |
3,475,262 | 3,475,444 | What causes a Sigtrap in a Debug Session | In my c++ program I'm using a library which will "send?" a Sigtrap on a certain operations when
I'm debugging it (using gdb as a debugger). I can then choose whether I wish to Continue or Stop the program. If I choose to continue the program works as expected, but setting custom breakpoints after a Sigtrap has been cau... | With processors that support instruction breakpoints or data watchpoints, the debugger will ask the CPU to watch for instruction accesses to a specific address, or data reads/writes to a specific address, and then run full-speed.
When the processor detects the event, it will trap into the kernel, and the kernel will se... |
3,475,317 | 3,475,328 | Class or Container to store heterogenous items in C++ | Is there any structure or class or container which i can use to store heterogenous items which is serializable. For example say i have a int,float and another class object. I want to store all of them in a particular container at runtime and pass it across classes. Does C++ give any such options.
| You could use a vector of boost::variant, e.g.
#include <boost/serialization/vector.hpp>
#include <boost/serialization/variant.hpp>
// note: the above are serializable variants of
// #include <vector>
// #include <boost/variant.hpp>
#include <fstream>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#incl... |
3,475,323 | 3,475,838 | how to show both icon and text on button on mfc? | Code Used:
m_pButton->Create(L"ABC", WS_CHILD | WS_VISIBLE| BM_SETIMAGE,CRect(0,0,100,100),this,ID_BUTTON1);
m_pButton->SetIcon(::LoadIcon(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_ICON1)));
//above Code show neither showing image nor showing text.
| BM_SETIMAGE is not a button style, but a message which is sent to the window in order to set a bitmap.
What you probably want is the BS_BITMAP style. Unfortunately as far as I know, it is not possible to have both text and a bitmap on a standard button. But you should find plenty of working implementations of a custom ... |
3,475,637 | 3,476,234 | Making a crash log meaningful (c++, Linux env) | I have a compiled c++ application that produces a stack trace when it crashes. At the moment, the stack trace isn't particularly meaningful. I would like to process it so that it contains symbols, rather than addresses.
Does anyone have any pointers on how I might go about doing this?
| If you have a map file its quite easy to map symbols to the addresses in the stack dump.
I wrote an article (including some sources) about this sometime ago at ddj:
http://www.drdobbs.com/tools/185300443
|
3,475,684 | 3,476,342 | Possible to abstract this logic with macro? | I have thousands of function wrappers which inside actually perform a similar logic like:
// a, b, ... are variable length parameters of different type
void API_Wrapper(hHandle, a, b, ..)
{
if (hHandle)
return remote_API(hHandle, a, b, ..);
else
return API(a, b, ..);
}
I want to use a macro to reuse the if-else... | Another trick, without variadic macro's:
#define API_CALL(hHandle, api_name, arguments) if (hHandle) return remote_##api_name arguments; else return api_name arguments;
void API_Wrapper(int hHandle, int a, double b, char c)
{
API_CALL(hHandle, api_name, (a, b, c));
}
Which becomes:
void API_Wrapper(int hH... |
3,475,764 | 3,475,813 | What is the reason for #pragma once inside header guards? | Just seen this inside <boost/asio.hpp>
#ifndef BOOST_ASIO_HPP
#define BOOST_ASIO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
/// ....
#endif // BOOST_ASIO_HPP
Disregarding the _MSC_VER preprocessor checks, what is the benefit of having the #pragma ... | #pragma once specifies that the file will be included (opened) only once by the compiler when compiling a source code file. This can reduce build times as the compiler will not open and read the file after the first #include of the module.
If you don't #pragma once, the file will be opened each time it is needed and co... |
3,475,841 | 3,475,951 | Signed / unsigned comparison and -Wall | I have recently started using the -Wall compiler switch in an attempt to improve the quality of my code. It is giving (correctly) a warning about this little snippet...
int i;
for (i = start - 1; i >= 0; i--)
{
if (i >= number1.array.size())
{
one_value = 0;
}
because n... | "Since the test in the loop is i >= 0, i has to be signed or it doesn't work." Just change your test like this:
for(unsigned i = start; i--;) {
// ...
}
Gives you the same value of i in the loop body.
|
3,475,920 | 3,476,008 | Using class member function as Callback | In PortAudio's C++ bindings, there is a MemFunCallBackStream constructior that can be called as:
portaudio::MemFunCallbackStream<MyClass> streamRecord(paramsRecord,
*AnInstanceOfMyClass,
&MyClass::MemberFunction);... | This FAQ seems to suggest that you can omit the & (for static member functions, at least), but then goes on to give various reasons why you shouldn't confuse ordinary function-pointers with C++ member-function-pointers.
EDIT: Found more information here, which is relevant to non-static member functions:
Some compilers... |
3,476,093 | 3,476,562 | Replacing ld with gold - any experience? | Has anyone tried to use gold instead of ld?
gold promises to be much faster than ld, so it may help speeding up test cycles for large C++ applications, but can it be used as drop-in replacement for ld?
Can gcc/g++ directly call gold.?
Are there any know bugs or problems?
Although gold is part of the GNU binutils since ... | At the moment it is compiling bigger projects on Ubuntu 10.04. Here you can install and integrate it easily with the binutils-gold package (if you remove that package, you get your old ld). Gcc will automatically use gold then.
Some experiences:
gold doesn't search in /usr/local/lib
gold doesn't assume libs like pthre... |
3,476,265 | 3,476,298 | Can not get example compiled with typedef in template class | I have this example code:
#include
template<class T>
class Class
{
public:
typedef boost::shared_ptr<Class<T> > Ref;
};
template<class T>
class Class2
{
public:
Class<T>::Ref getAReference() {return Class<T>::Ref(new Class<T>);};
};
int main(){}
When I try to compile it, I get:
test.cpp:14: error: type ‘... | You need to tell the compiler that Ref is a type by using typename i.e.
typename Class<T>::Ref getAReference() {return Class<T>::Ref(new Class<T>);};
This question discusses it further.
|
3,476,590 | 3,476,703 | Would it break the language or existing code if we'd add safe signed/unsigned compares to C/C++? | After reading this question on signed/unsigned compares (they come up every couple of days I'd say):
Signed / unsigned comparison and -Wall
I wondered why we don't have proper signed unsigned compares and instead this horrible mess? Take the output from this small program:
#include <stdio.h>
#define C(T1,T2)\
{sig... | Yes it would break the language/existing code. The language, as you have noted, carefully specifies the behavior when signed and unsigned operands are used together. This behavior with comparison operators is essential for some important idioms, like:
if (x-'0' < 10U)
Not to mention things like (equality comparison):
... |
3,476,675 | 3,476,682 | How does a variable in C/C++ work? | How does a variable in C/C++ work?
I mean, a pointer stores an address from a variable and then you have to dereference it to access the object to which it refers, so I think that a variable is a pointer that is dereferenced automatically when used... does that make any sense?
| A variable is an abstraction (a convenient name) for a memory position on the computer. In C/C++ if the variable is of type int it will be a convenient name for a memory address holding an integer value.
And a variable is not a pointer automatically dereferenced. A variable just holds the value it is supposed to hold. ... |
3,476,869 | 3,476,902 | g++ linker: /usr/lib/libGL.so.1: could not read symbols: Invalid operation | I'm trying to build a very simple OpenGL-app under Ubuntu 10.04 (I have a 32 bit system).
When I'm trying to compile the file, I get the error message:
g++ -L/usr/lib simple.cpp -lglut
/usr/bin/ld: /tmp/ccoPczAo.o: undefined reference to symbol 'glEnd'
/usr/bin/ld: note: 'glEnd' is defined in DSO //usr/lib/libGL.so.1 s... | You need to include the opengl library on the command line as well as the glut library/.
Try adding -lGL to the end of your command line
g++ -L/usr/lib simple.cpp -lglut -lGL
|
3,476,938 | 3,477,305 | Example to use shared_ptr? | Hi I asked a question today about How to insert different types of objects in the same vector array and my code in that question was
gate* G[1000];
G[0] = new ANDgate() ;
G[1] = new ORgate;
//gate is a class inherited by ANDgate and ORgate classes
class gate
{
.....
......
virtual void Run()
{ //A virtual fu... | Using a vector of shared_ptr removes the possibility of leaking memory because you forgot to walk the vector and call delete on each element. Let's walk through a slightly modified version of the example line-by-line.
typedef boost::shared_ptr<gate> gate_ptr;
Create an alias for the shared pointer type. This avoids ... |
3,476,939 | 3,511,101 | Is there a Click Handler for Shell Extension | After going through MSDN Shell Extensions I am not quite sure if I can extend the behaviour of Shell Click or Click Event of explorer. Any suggestion or Code Snipet, article or Walk through?
| There is no such possibility. That would make the shell too vulnerable. Imagine all the malware that exploits this functionality.
If you want to capture the click event, there is no easy way. You may SetWindowsHookEx and monitor/capture mouse messages for all windows of CabinetWClass and/or DirectUIHWND class. You may ... |
3,477,174 | 3,477,251 | Problem with template specialisation for a derived class | When I compile the following
#include <iostream>
#define XXX 1
#define YYY 2
class X
{
public:
template< int FLD >
void func();
};
template<> void X::func< XXX >()
{
std::cout << "X::func< " << XXX << " >" << std::endl;
}
class Y : public X
{
public:
};
template<> void Y::func< YYY >()
{
std::cout... | You cannot do it, as you cannot do the following either and for the same reason, Y::func is not declared in Y:
class X {
public:
void foo();
};
void X::foo() {}
class Y : public X {
};
void Y::foo() {}
|
3,477,270 | 3,477,330 | Effective C++: Item 52 and how to avoid hiding all normal operator new & delete versions | At the end of Item 52 (Customising new and delete) in Myer's Effective C++ he discusses how to avoid hiding normal new and delete versions when implementing custom version as follows:
If you declare any operator news in a
class, you'll hide all these standard
forms. Unless you mean to prevent
class clients from... | That would effectively be a no-op using. He's simply showing an implementation of the base class new/delete that would duplicate the normal behavior.
Usually if you're creating a custom new and delete you would have changed behavior in that base class and the using ::operator new; would no longer be equivalent. He didn... |
3,477,449 | 3,477,521 | Call the constructor of the unknown children | I want to call the constructor;
class anAbstractClass
{
public: anAbstractClass(inputdatatype){/*blablabla*/}
};
class aChield : public anAbstactClass
{
/*
...
*/
}
void _engine::initShader(_anAbstractClass** inShader)
{
*inShader = new /*???*/(inputdata for the construcor)
}
aChield* theChield;
_engine* myEngi... | Nice idea, but there is no support to get the exact type of a pointer at runtime.
In your initShader method, inShader is of type anAbstractClass** and there is no way to get the information that it was a pointer to pointer to a derived class before the method call.
So you need the change your code, maybe you can use so... |
3,477,525 | 3,477,578 | Is it possible to use a C++ smart pointers together with C's malloc? | Some of my code still uses malloc instead of new. The reason is because I am afraid to use new because it throws exception, rather than returning NULL, which I can easily check for. Wrapping every call to new in a try{}catch(){} also doesn't look that good. Whereas when using malloc I can just do if (!new_mem) { /* han... | If you are using shared_ptr or unique_ptr, you can specify a custom deleter. For example,
struct free_delete
{
void operator()(void* x) { free(x); }
};
This can be used with shared_ptr like so:
std::shared_ptr<int> sp((int*)malloc(sizeof(int)), free_delete());
If you are using unique_ptr, the deleter is a part o... |
3,477,546 | 3,477,575 | Can I use C/C++ code inside my ActionScript-3 code? | I wonder if there is ways for communicate actionscript with c/c++, as well as the level of complexity..
| You're looking for Adobe Labs Alchemy:
Welcome the preview release of codename "Alchemy." Alchemy is a research project that allows users to compile C and C++ code that is targeted to run on the open source ActionScript Virtual Machine (AVM2). The purpose of this preview is to assess the level of community interest in... |
3,477,555 | 3,520,218 | Table of conversion of ISO-639/ISO-3166 based language/country locale name to Windows ones and back | I want to convert POSIX locale names like en_US, de_DE that use
ISO-639-1 and ISO-3166 codes
to Windows ones English_United States, German_Germany and back.
I had found following tables on MSDN site:
Languages http://msdn.microsoft.com/en-us/library/39cwe7zf(v=VS.71).aspx
Countries http://msdn.microsoft.com/en-us/libr... | I think I had found the answer: http://msdn.microsoft.com/en-us/library/cc233965.aspx
This documents includes locale ids, their names and ISO codes...
|
3,477,741 | 3,477,952 | Why does C++ require a cast for malloc() but C doesn't? | I have always been curious about this - why do in C++ I have to cast return value from malloc but not in C?
Here is the example in C++ that works:
int *int_ptr = (int *)malloc(sizeof(int*));
And here is the example in C++ that doesn't work (no cast):
int *int_ptr = malloc(sizeof(int*));
I heard that in C, in fact, ca... | Several points:
C allows void pointers to be implicitly converted to any other object pointer type. C++ does not.
Casting the result of malloc() in C will supress a useful diagnostic if you forget to include stdlib.h or otherwise don't have a declaration for malloc() in scope. Remember that if C sees a function ca... |
3,477,955 | 3,477,973 | "vector iterator not incrementable" run-time error with set_intersection | Why does this code result in a run-time error "vector iterator not incrementable"?
vector<string> s1, s2;
s1.push_back("joe");
s1.push_back("steve");
s1.push_back("jill");
s1.push_back("svetlana");
s2.push_back("bob");
s2.push_back("james");
s2.push_back("jill");
s2.push_back("barbara");
s2.push_back("steve"... | result.begin() of an empty vector is not a valid output iterator. You need a back_inserter(result) instead.
#include <iterator>
...
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), back_inserter(result));
cout << result.size() << endl;
Alternatively, resize result to at least 4, so that the vector can con... |
3,478,046 | 3,482,091 | Why isn't main defined `main(std::vector<std::string> args)`? | This question is only half tongue-in-cheek. I sometimes dream of a world without naked arrays or c strings.
If you're using c++, shouldn't the preferred definition of main be something like:
int main(std::vector<std::string> args)
?
There are already multiple definitions of main to choose from, why isn't there a vers... | A concern that keeps coming back to my mind is that once you allow complex types, you end up with the risk of exceptions being thrown in the type's constructor. And, as the language is currently designed, there's absolutely no way for such an exception to be caught. If it were decided that such exceptions should be c... |
3,478,054 | 3,478,115 | What is the interface that change the cpu frequency and the core voltage on the windows platform? | I want to find the interface supplied by windows to change the CPU frequency and core voltage.
Thanks!
| From Windows Native Processor Performance Control(document link)
Parameters to P-state policy
Several parameters to Windows processor performance state controls are configurable via registry keys. These keys are provided with the intent that OEMs and system designers may tune the performance of Windows processor powe... |
3,478,180 | 7,389,054 | correct usage of GetClipRgn? | I want to write a function that needs to set the clipping region on a DC but restore any existing clipping region on the DC when it is done.
So I found GetClipRgn which sounds like exactly what I want but seems confusing. I couldn't find any examples of using it and Petzold had nothing to offer.
What I came up with wa... | Well the closest thing to a correct answer is Hans Passant's comment:
Yeah, it's a weird function. Your code looks okay.
|
3,478,344 | 3,479,821 | iOS 4 VOIP app responding in the background | I have an iPhone VOIP app that copes with multi-multi transmit and receive (ie teleconferencing) set up using BSD sockets. I would like it to be able to respond to incoming requests when it is in the background but from what I can understand of the iOS 4 docs I can only do this on an NSStream object (or CFRead/WriteSt... | You can create a socket from a file descriptor with CFSocketCreateWithNative(), and then create a pair of streams with CFStreamCreatePairWithSocket(). It might let you use them on a UDP socket. Provided the streams don't read data unless you ask, you might be able to get away with using the FD directly.
Good luck with ... |
3,478,377 | 3,478,408 | Return private array | I've a class and there is an array set as private. How do I make the get_array() function? I mean, how do I return that array knowing that I will have to return a pointer of arr[0] as we know , but isn't this breaking the private rule? Is there another way of returning this array?
I actually thought of having array2 in... | I would use std::vectors instead of arrays in C++. You can return them just like a primitive (vector<whatever> getter(){ return foo;}), and they tend to be easier to deal with.
|
3,478,403 | 3,479,218 | IMemAllocator:GetBuffer hangs | Does anybody know any reasons why IMemAllocator:GetBuffer (Directshow) hangs, apart from all samples being in use?
I have a directshow application which uses GMFBridge by Geraint Davies to connect two graphs. The GMFBridge is used to be able to switch inputs, but I am not switching in this situation. The application ca... | Not sure that I can debug this from the info given. Can you create a log file (create an empty file c:\gmfbridge.txt, run until it hangs, then zip the file and email it). Also, if you set up your symbols with _NT_SYMBOL_PATH, you could look at the stack trace to see where in quartz.dll the various threads are.
G
|
3,478,632 | 3,479,568 | How to get BS_DEFPUSHBUTTON to work? | My button has these styles:
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON
it creates and lights up properly, but in my edit control, when i press ENTER, it does nothing!
Heres the styles of my edit control:
WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | WS_TABSTOP
I am not using a dialog, i have created my windows... | It might be that your button is not set to be default. One solution could be to set the default button behavior with the DM_SETDEFID
/*
in: win: HWND of the window you have
in: id: your id of your default button
*/
SendMessage(win, DM_SETDEFID, id, 0);
|
3,478,879 | 3,478,965 | Expected constant expression fails miserably in switch statement | Say I have a class "Code" defined like this, with a user specified type conversion to int:
class Code
{
public:
int code;
std::string description;
Code (const int c, const std::string& d) : code(c), description(d) { ; }
operator int() const { return code; }
};
And a second class "Master" using th... | The labels in a switch statement must be "integral constant-expressions" (§6.4.2/2). An integral constant expression" is defined as (§5.19/1):
An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constan... |
3,478,986 | 3,479,050 | template template total specialization | A template template specification is like this:
template < template < class > class T >
struct MyTemplate
{
};
How am I supposed to create a total (or partial) specialization for this template?
Is this possible?
| Like this:
#include <iostream>
template <typename T>
struct foo{};
template <typename T>
struct bar{};
template < template < class > class T >
struct MyTemplate
{
static const bool value = false;
};
template <>
struct MyTemplate<bar>
{
static const bool value = true;
};
int main(void)
{
std::cout << s... |
3,479,014 | 3,479,053 | Passing Template parameters | I am trying to understand templates better
I have a template class that starts like this in my .h:
template <class DOC_POLICY, class PRINT_POLICY, class UNDO_POLICY>
class CP_EXPORT CP_Application : public CP_Application_Imp
Now I need to initialize so in my .cpp so I do:
CPLAT::CP_DocumentPolicy_None * d = new CPLAT:... | I believe it should work
CPLAT::CP_Application<CPLAT::CP_DocumentPolicy_None,CPLAT::CP_PrintPolicy_None,CPLAT::CP_UndoPolicy_None>::Init(d,p,u);
|
3,479,092 | 3,479,409 | Wrapping linked lists in iterators | A set of APIs that I commonly use follow a linked-list pattern:
struct SomeObject
{
const char* some_value;
const char* some_other_value;
SomeObject* next;
}
LONG GetObjectList( SomeObject** list );
void FreeObjectList( SomeObject* list );
This API is not mine and I cannot change it.
So, I'd like to e... |
You would make MyObjectIterator a friend of MyObject. I don't see any better way. And really I think it's reasonable that iterators get whatever special friend access is necessary for them to perform their duties.
You don't seem to have considered how and where your MyObject instance are going to be stored. Or perhaps... |
3,479,160 | 3,479,169 | What does this C++ statement mean? | void max_idxs(vector<int> &pidxs){
vector<fragment *> ids;
max_ids(ids);
for(size_t i = 0; i < ids.size(); i++){
int weight_idx = ids[i]->weight_idx; //Get weight index
}
}
In this C++ code, what does it mean by int weight_idx = ids[i]->weight_idx;?
What does -> mean?
Thanks!
| x->y means (*x).y. In other words, "take the address pointed to by x, and get the variable y from the object there". Here, it means it'll get the weight_idx from the fragment pointed to by ids[i].
|
3,479,278 | 3,479,427 | In C++, how can you avoid explicit downcasts with a map of generic types? | This is a little contrived, but say I have a class interface like this:
class IResource;
class IResourceContainer
{
public:
virtual ~IResourceContainer() {}
virtual void AddResource(const std::string& rStrName,
std::auto_ptr<IResource> apResource)=0;
virtual IResource& GetReso... |
is there a better way of holding pointers to generic types that don't require explicit downcasts from the user?
No.
Either you're using classic OO, a.k.a. run-time polymorphism. Then you are stuck with base class interfaces or you have to cheat and down-cast. Or you use templates, a.k.a. compile-time polymorphism. T... |
3,479,485 | 3,479,573 | Is there a built-in function that comma-separates a number in C, C++, or JavaScript? | Given a number 12456789, I need to output 12,456,789 without much coding. Are there any built-in functions in either C, C++, or JavaScript I can use to do that?
| I found this little javascript function that would work (source):
function addCommas(nStr){
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;... |
3,479,674 | 3,479,764 | porting ostream::opfx / osfx from Unix to Linux | I am porting some C++ code from Unix to Linux (Red Hat).
I have run into the following pattern:
ostream& myfunction(ostream& os)
{
if (os.opfx())
{
os << mydata;
os.osfx();
}
return os;
}
The functions opfx and osfx are not available under Red Hat 4.5. I saw a suggestion here to use the ostream::sentr... | Any existing inserter (unless it's really horribly buggy) is already doing to create a sentry object, so as long as your do your work via an existing inserter, you don't need to create a sentry object yourself.
You do need to create a sentry object when you write your data directly to the stream buffer on your own, wit... |
3,479,712 | 3,479,735 | Virtual Functions Object Slicing | My question is with reference to this question which explains how virtual functions work in case of object slicing which end up calling base class virtual function and Wikipedia article which explains the virtual table layout for a derived class for below code
class A{
public:
virtual void func(){ cout<<"... | "Virtual table for class B"? Virtual table for class B is not involved in oA.func() call at all. Object oA has type A, which means that its virtual table is that of class A.
Moreover, most compilers will optimize the oA.func() call so that it won't use any virtual tables at all. Since the type of oA is known at compile... |
3,479,824 | 3,479,876 | How to save QListView items to file | How to save QListView items to text file?
| Access the elements via the underlying Item Model and write them to the file in whatever way makes sense in the context of your program.
EDIT for more detail:
I'm a little rusty in my Qt experience right now, so I don't have an exact snippet of code. Furthermore, there's probably more than one way to go about doing th... |
3,479,894 | 3,479,999 | How to make a "calculated attribute" for a C++ class using templates | I'm trying to implement generic method to put in a class a calculated value as a read-only memver value.
I've successfuly acomplished it using the following macro:
#define READONLY_PROPERTY(datatype, containerclass, access, name)\
class name ## _ ## datatype ## _ROP {\
public:\
name ## _ ## datatype ## _ROP(con... | because getPix() was not declared when it is used as a template parameter, and _instance have to be const because ReadOnlyProperty constructor parameter is const.
template< class T, class U, U (T::*F)() const >
class ReadOnlyProperty {
public:
ReadOnlyProperty(T const& instance): _instance(instance) {}
operator... |
3,480,320 | 3,480,333 | What does the :: mean in C++? | void weight_data::rev_seq(string &seq){
//TODO
std::reverse(seq.begin(), seq.end());
}
In this C++ method, I think this method does not return anything, so the prefix is void, what does :: tell the relationships between weight_data and rev_seq(string &seq)? Thanks!
| void is the return type. :: is the scope resolution operator, so it means rev_seq is inside the scope of weight_data. weight_data could be either a namespace or a class (based on what you've given, it's not possible to say which).
|
3,480,722 | 3,480,752 | C++ Vector/list of priority queues? | Why wouldn't C++ allow something like that ?
I need to have multiple priority queues, the number of which would be determined at run time.
This fails to compile
std::vector<std::priorityqueue<Class A>>.
Is there a better approach ?
| This should work just fine. Just the syntax should be:
std::vector<std::priority_queue<A> >
(note the space (" ") near the end.
|
3,480,837 | 3,480,847 | key comparisons in c++ map not working | I have created a map with ClassExpression as the key and std::string as the value. The key comparator is given below
class ClassExpressionComparator {
public:
bool operator()(const ClassExpression& lhs,
const ClassExpression& rhs) const {
return ((lhs.quantifier == rhs.quantifier) &&
... | You wrote an equality comparison. map requires a less-than comparison. (Or greater-than if you want the keys in decreasing order.)
My usual idiom for doing this:
bool operator()(const ClassExpression& lhs,
const ClassExpression& rhs) const {
return lhs.quantifier < rhs.quantifier? true
: rhs.quantifi... |
3,481,026 | 3,481,082 | inheriting from a template class causes errors | I have a template class MyTemplate. It works fine. But as soon as I create another class that derives from it, I get errors.
//main.cpp
template <typename T> class MyTemplate {
public:
T* test() {
return new T(this); //error here.
}
};
template <typename T> class MyTemplate2 : public My... | What you try is simply to pass a Base* (which is this) to a Derived*, which is the wrong way around. You need to explicitly cast to perform this downward conversion.
|
3,481,089 | 3,481,354 | Boost multi_index composite keys using MEM_FUN | Is there a way to use member functions in the specification of composite_key's in boost multi_index_container's?
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/m... | It looks like you're trying to tag the key extractors in the composite case, but I think you can only tag indexes. I think what you want is to replace
ordered_non_unique<
composite_key<
Name,
member<tag<last>, BOOST_MULTI_INDEX_CONST_MEM_FUN(Name, const string &, last)>,
... |
3,481,145 | 3,481,330 | C++\Win32 API - Load controls at run-time from xml | Is there a library that can load controls (buttons, text boxes, etc.) from an xml file? Kind of like in WPF.
| Qt's resource files (*.qrc) are quite similar to XML (though they lack an XML header, so they're not truly proper XML). At least if memory serves, they get parsed and translated to C++ at build-time, so once the application is built, the UI is "fixed".
wxWidgets has an XML-based resource system (XRC, if memory serves) ... |
3,481,548 | 3,502,632 | Why do we need "this pointer adjustor thunk"? | I read about adjustor thunk from here. Here's some quotation:
Now, there is only one QueryInterface
method, but there are two entries, one
for each vtable. Remember that each
function in a vtable receives the
corresponding interface pointer as its
"this" parameter. That's just fine for
QueryInterface (1); ... | Taking away the COM part from the question, the this pointer adjustor thunk is a piece of code that makes sure that each function gets a this pointer pointing to the subobject of the concrete type. The issue comes up with multiple inheritance, where the base and derived objects are not aligned.
Consider the following c... |
3,481,594 | 3,481,607 | How to program a super simple software activation system? | I have a piece of shareware that I wrote that I'd like to distribute on the internet. I have a serial number type thing set up but there is still a ton of key sharing :(. I'd like to add a system where once the user enters the serial, it is checked with my server to make sure that it is valid. Simplicity is key.
-Clie... | There are actually several blatant security holes in your scheme.
The first is that users can redirect their local internet traffic to a site that pretends to be you, but always displays a "1".
The second is that each key would only be good for X "activations", but if the message is lost in transit, too bad - the count... |
3,481,713 | 3,481,766 | How to get started with directshow? | I'm having a great trouble trying to understand this,
what's the least set up to compile/run directshow apps?
I've already installed visual c++ 2008 express.
A hello world will be nice,
RGS!
| Try downloading SDK such as Windows SDK "http://www.microsoft.com/downloads/details.aspx?FamilyID=6b6c21d2-2006-4afa-9702-529fa782d63b&displaylang=en".
There are usually a bunch of samples for directshow. But, mainly they either use commandline "nmake" (not make) or "cl" (not cc or gcc) to build. Sometimes they provide... |
3,481,775 | 3,481,783 | Compile-time assertions in C++? | I recently came upon the need to have compile-time assertions in C++ to check that the sizes of two types were equal.
I found the following macro on the web (stated to have come from the Linux kernel):
#define X_ASSERT(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
which I used like so:
X_ASSERT(sizeof(Botan::by... | You might want to take a look at Boost StaticAssert. The internals aren't exactly clean (or weren't the last time I looked) but at least it's much more recognizable, so most people know what it means. It also goes to some pains to produce more meaningful error messages if memory serves.
|
3,481,856 | 3,506,654 | Sending variable pointers back and forth between C++ and Lua? | I am looking for a way to transfer the variable addresses back and forth between C++ and Lua. For instance, transferring an object from C++ to Lua and do some processing, then transfer it back to C++.
However, the thing is how can you execute a C++ functions or methods from Lua? Or is a workaround required?
If possibl... | It took me a lot of fiddling around to get Lua to work well with C++ classes. Lua is much more of a C style API than C++ but there are plenty of ways to use it with C++.
In the Lua C API a pointer is represented by userdata (or light userdata which have no metatables and are not garbage collected). Userdata can be as... |
3,482,064 | 3,482,093 | counting the number of lines in a text file | I'm reading lines off of text file and I'm wondering if this is a good way to go? I had to write the function numberoflines to decrease the number_of_lines variable by one because within the while loop, for every line it read it adds 2 to the number_of_lines variable.
#include <iostream>
#include <fstream>
using namesp... | Your hack of decrementing the count at the end is exactly that -- a hack.
Far better to write your loop correctly in the first place, so it doesn't count the last line twice.
int main() {
int number_of_lines = 0;
std::string line;
std::ifstream myfile("textexample.txt");
while (std::getline(myfile, li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.