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 |
|---|---|---|---|---|
6,185,340 | 6,185,410 | specifying type of a class member in template function | I have this template function:
template <class P>
double Determinant(const P & a, const P & b, const P & c) {
return (b.x-a.x)*(c.y-a.y) - (c.x-a.x)*(b.y-a.y);
}
but I want to avoid forcing the return type to double all the time -- P::x and P::y could be ints too, and I need this function in both situations. Is t... | Compiler cannot deduce return-type of function template, from function argument. Type deduction is done with function arguments only.
In C++03, you can define typedef in your class as:
struct A //suppose A is going to be type argument to your function template
{
int x, y; //I'm assuming type of x and y is same!
... |
6,185,662 | 6,186,322 | Qt - A simple echo server | How in Qt would you keep a thread alive in the QThreadPool; as far as I've seen there is only an option to run a QRunnable and I've been told they can't control the thread they are within. How would I, using the thread pool keep a socket alive and ready to read and write?
| QThreadPool manages its own threads. QT Doc says that
QThreadPool manages and recyles
individual QThread objects to help
reduce thread creation costs in
programs that use threads.
So you should not try to keep a thread alive. That breaks the purpose of thread pool.
Also QT sockets are designed to work well wi... |
6,185,957 | 6,186,019 | Rethrowing exceptions | Why doesn't the following doesn't handle the exception that was rethrown? I tried all the combinations but none of them would show the output in last catch so I'm confused!
Derived D;
try {
throw D;
} catch ( const Derived &d) {
throw;
} catch (const Base &b) {
cout << "caught!" << endl;
}
Derive... | The re-throw is not handled by the same try-catch block. It's thrown up to the calling scope.
In [except.throw] (2003 wording):
A throw-expression with no operand rethrows the exception being handled.
and:
When an exception is thrown, control is transferred to the nearest handler with a matching type (15.3);
“near... |
6,185,975 | 6,186,210 | Prevent user process from being killed with "End Process" from Process Explorer | I noticed that GoogleToolbarNotifier.exe cannot be killed from Process Explorer. It returns "Access Denied". It runs as the user, it runs "Normal" priority, and it runs from Program Files.
How did they do it?
I think there might be a way to modify the ACL, or mark the process as 'critical', but I cannot seem to locat... | When running my copy of that has Deny set on the Terminate permission (Process Explorer shows this).
Presumably they call SetKernelObjectSecurity to change/remove the ACLs when their process loads.
|
6,186,301 | 6,189,661 | Pouring Water, where goes wrong? | I have finished Pouring Water from SPOJ. However, the system keeps giving wrong answer. But I cannot find out where goes wrong.
Please give a hint. Test cases are also appreciated.
#include <iostream>
int countFromA (int a, int b, int c);
int main() {
int t;
std::cin>>t;
std::cin.ignore(5, '\n'); // SPOJ ... | Here is a hint. Since this is a coding exercise for your benefit I won't give you the full answer.
You have 4 different operations that you might need to combine in any sequence to get your answer. Suppose that your numbers are 21, 3, 15. You need to look at both repeatedly dumping b into a until you have 15 in ther... |
6,186,550 | 6,186,600 | Store objects of three different classes in an array | This is an interview question:
how can we store the objects of let's say 3 different classes which are totally independent of each other.
My answer was:
create an array which stores all void pointers.
like :
void *array[];
and store the pointers of all the objects.the array elements can be many.
but for retrieving the... | Why are you trying to make this so complicated?
struct T {
T1 obj1;
T2 obj2;
T3 obj3;
};
If you instead mean that you have an array of objects, and each element can be of any of three distinct, unrelated types, then it's a silly interview question because it's a silly thing to do.
(Yes, you would consider rei... |
6,186,761 | 6,186,837 | should we delete the observer when unregister it? | Observer *o = New Observer();
Subject *s = new Subject() ;
s->register(o);
//Is it a good practice to delete the observer in the unregister function?
//I feel it is not. As the Observer object might still be in use, for example ,
//it might be registered to another Subject.
s->unregister(o);
//So it is safe to r... | I agree with your observation. It is not a good practice to delete the observer in the unregister function - for the simple fact that "one who creates the resource must be responsible for deleting the resource"
This will avoid
Magic behavior as perceived by the creator.
Code behavior will be well defined - one who cre... |
6,186,896 | 6,192,574 | Display custom image and have the ability to catch mouse input | I am trying to display several images in the MainWindow and have the ability to perform certain actions when these images receive mousePressEvent.
For this, I thought I would create a new class, derived from QWidget, which had a QImage private member. With this, I as able to override the paintEvent and the mousePressEv... | If you want to use QWidget you should take look at the mask concept to refine the space occupied by your images (be careful about the performance of this implementation).
If you decide to go with the QGraphicsItems you can re-implement the virtual method QPainterPath QGraphicsItem::shape () const to return a path repre... |
6,187,020 | 6,187,813 | Access Base class variable from child class method | How can I access base class variable from a child method? I'm getting a segmentation fault.
class Base
{
public:
Base();
int a;
};
class Child : public Base
{
public:
void foo();
};
Child::Child() :Base(){
void Child::foo(){
int b = a; //here th... | It's not good practice to make a class variable public. If you want to access a from Child you should have something like this:
class Base {
public:
Base(): a(0) {}
virtual ~Base() {}
protected:
int a;
};
class Child: public Base {
public:
Child(): Base(), b(0) {}
void foo();
private:
int b;
};
void Chi... |
6,187,310 | 6,201,204 | Parsing text from CMemFile line by line | I have got a huge text file loaded into a CMemFile object and would like to parse it line by line (separated by newline chars).
Originally it is a zip file on disk, and I unzip it into memory to parse it, therefore the CMemFile.
One working way to read line by line is this (m_file is a smart pointer to a CMemFile):
... | Using a profiler showed that 75 % of process time was wasted in this line of code:
ProcessLine(string(readBuffer, posNewline));
Mainly the creation of the temporary string caused a big overhead (many allocs). The ProcessLine function itself contains no code. By changing the declaration from:
void ProcessLine(const st... |
6,187,830 | 6,187,957 | Error when compiling cpp file |
Possible Duplicate:
C++: malloc : error: invalid conversion from ‘void*’ to ‘uint8_t*’
Hello,
I have this little function
Uint32 moveSprite(Uint32 interval, void *param)
{
SDL_Rect* spritePos = param;
spritePos->x++;
return interval;
}
The problem here is quite simple, I'm using codeblocks, when i sav... | Your code is valid C, not valid C++. You need to add an explicit casting for it to compile
Either C-style:
SDL_Rect* spritePos = (SDL_Rect *)param;
Or more C++-ish:
SDL_Rect* spritePos = static_cast<SDL_Rect *>(param);
A better solution would be to change the parameter type instead if that's possible for you. Avoid... |
6,187,835 | 6,188,027 | vector iterators incompatible | I'm currently working on a graph library for C++ and now got stuck at a point where I get an assertion error in debug mode during runtime. I also had a look an some other question here on SO but none of the questions and answers lead me to a solution. After reading in some forums I have the impression that this error h... | My guess, given limited context you provided, is that neighbours() returns copy of std::vector<edge*>, instead of reference, i.e. std::vector<edge*>&. So after begin() call temporary object is disposed, and obtained iterator points to rubbish.
|
6,188,069 | 6,189,268 | Anybody know any resources for adding your own language to visual studio 2010 that is not managed? | I've seen the MyC pages in code project and MS's Iron Python. Is there a simple sample for unmanaged code? I'd like to add a superset to C++.
Update
Eventually the code may not be convertible to C++ and so I would like to find a start to finish example of creating an unmanaged new language for VS including IDE support,... | Visual Studio extensions are usually (at least for nontrivial extensions) implemented as packages by deriving from the Package class from the SDK. Your package class is responsible for defining all of the capabilities that it provides.
You will need to implement a language service for IntelliSense, autocompletion, syn... |
6,188,549 | 6,188,590 | value becoming 0 for no obvious reason | for some reason, the value mod i am creating is becoming 0 in keygen despite being correct when it is made and after keygen is run. i dont get why. can anyone tell me?
class RC5{
private:
uint64_t w, r, b;
uint128_t mod;
std::string mode;
std::vector <uint64_t> S;
public:
... | erm, because in the ctor you are modifying a local variable called mod which shadows your class member.
|
6,188,620 | 6,188,670 | Guide to good text file IO C/C++ on linux | I often find myself needing to write functions to load/save from/to ASCII (or similar) text files; such as config files or data. I can and have done so many times but never feel like I do it well. ie the results are not very tolerant of minor changes to the file format.
Can anyone point me to a good guide to writing ro... | Off the top of my head, there's:
Glib's key-value file parser
YAML
Both of these are pretty standard under linux.
|
6,188,907 | 6,189,009 | timespec on windows compilers | On posix it is possible to use timespec to calculate accurate time length (like seconds and milliseconds). Unfortunately I need to migrate to windows with Visual Studio compiler. The VS time.h library doesn't declare timespec so I'm looking for other options. As far as could search is it possible to use clock and time_... | The function GetTickCount is usually used for that.
Also a similiar thread: C++ timing, milliseconds since last whole second
|
6,189,096 | 6,189,124 | Standard reference for int foo = foo | int foo = foo; compiles.
Which part of the C++ standard allows this?
|
3.3.1 Point of declaration [basic.scope.pdecl]
The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any),
The behaviour is well defined if the declaration is at file scope. If you have the ... |
6,189,155 | 6,189,331 | static_cast dynamic_cast: expected constant expression? | In visual C++ 2010, when compiling the following codes, I get error message:
static_cast error C2057: expected constant expression.
what's wrong with that?
struct A {};
struct B : A {};
struct XX
{
static const int offset = (long)static_cast<A*>((B*)0x8) - 0x8;
};
Thanks AProgrammer, the following is correct for ... | Your casts to A* and B* prevent the initializer of x to be a constant expression:
5.19/3
Cast operators in an arithmetic constant expression shall only convert arithmetic or enumeration types to arithmetic or enumeration types, excepted as part of an operand to the sizeof operator.
which is needed in that context:
9... |
6,189,183 | 6,192,079 | How to draw cube at some world coordinates, OpenGL | I have this code that doing this, but it don't work at all!
GLdouble *posv = Utils::worldToScreen(px, py, pz);
GLdouble x = posv[0];
GLdouble y = posv[1];
GLdouble z = posv[2];
GLdouble *sizev = Utils::worldToScreen(1.0f, 1.0f, 1.0f);
GLdouble sizex = sizev[0];
GLdouble sizey = sizev[1];
GLdouble sizez = sizev[2];
glB... | Rather than drawing vertices at x+/-size, y+/-size, z+/-size, why don't you just translate to x, y, z with glTranslatef() and then do your drawing?
Try this as your draw function:
void drawCube(float x, float y, float z)
{
const float sizex = 0.5f;
const float sizey = 0.5f;
const float sizez = 0.5f
glT... |
6,190,105 | 6,190,216 | FormatMessage with placeholders |
CString ErrorMessageFromErrorCode(DWORD errorCode)
{
void* pMsgBuf = NULL;
::FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &pMsgBuf,
0,
NULL);
CString... | Try adding FORMAT_MESSAGE_IGNORE_INSERTS to the flags.
|
6,190,478 | 6,190,533 | Array of THREADENTRY32 struct as function parameter causes C2061 | I want to add a method to my debugger which fills a THREADENTRY32 array with all threads of the process being currently debugged. For that, I want to use the method "EnumerateThreads" which I pass a THREADENTRY32 pointer which the function should fill out.
However, I'm having trouble using a THREADENTRY32 pointer as a ... | try using:
void EnumerateThreads(struct THREADENTRY32 *threadArray);
this will inline forward declare the struct, however, you need the full definition from Tlhelp32.h where ever you access the members of the struct or use the sizeof operator.
alternatively you need to declare the struct (by including the Tlhelp32.h) ... |
6,190,624 | 6,190,830 | UVA 10189: Minesweeper | Here's the link to the problem: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=13&page=show_problem&problem=1130
This is my code and it works perfectly; however, it gives wrong answer whenever I submit it. Does anybody know why?
NOTE: I pad the matrix with 2 extra rows and columns so that... | No attempt is made to clear out arr[][] between runs (or clear at start), so a 4x4 minefield with a * in the 4th position will cause a next 3x3 minefield to have incorrect values.
|
6,190,928 | 6,193,129 | Can I keep a certain functions from being inherited in C++ | Sample code
#include <iostream>
using namespace std;
class Base
{
public:
virtual void Func()
{
cout << "\nIn base func";
}
};
class Derived : public Base
{
public:
void Func()
{
cout << "\nIn derived";
}
};
class Derived2 : public Derived
{
public:
void Func()
{
... | No; C++ has no equivalent to C#'s sealed modifier.
|
6,190,963 | 6,191,216 | C++ macro to convert a string to list of characters | Is it possible to have a macro to have:
CHAR_LIST(chicken)
to expand to:
'c', 'h', 'i', 'c', 'k', 'e', 'n'
[Reason I want it: because for even moderate-sized strings, a macro is hugely more convenient than manually expanding. And the reason I need to expand is passing in a string to a varidiac template]
| Update by the answerer, July 2015: Due to the comments above on the question itself, we can see the the real question was not about macros per se. The real problem the questioner wanted to solve was to be able to pass a literal string to a template that accepts a series of chars as non-type template arguments. Here is ... |
6,191,031 | 6,191,069 | Proper way to manage C++ include directives | I'm a little confused about how C++ handles includes.
I have something like:
typedef struct {
//struct fields
} Vertex;
#include "GenericObject.h"
Now in GenericObject.h I have:
class GenericObject {
public:
Vertex* vertices;
}
When I try to compile, the compiler says:
ISO C++ forbids declaration of 'Verte... | Two things, first you want it to just be...
struct Vertex
{
//struct fields
};
That is a properly defined struct in C++.
Now you either need to include Vertex.h, or what ever file contains the vertex struct, in your generic object header,
#include "Vertex.h"
class GenericObject {
public:
Vertex* vertices;
};
or f... |
6,191,055 | 6,191,106 | Would an MSI able to launch programs/files with elevated permissions automatically? | I am trying to make it possible for an .msi file to open an executable which will register a Browser Helper Object. Since this involves writing to the registry, cmd.exe must be elevated with administrative privelages. I am able to manipulate the ShellExecute() function to make a UAC dialog pop up and ask whether the us... | My understanding is that IF UAC is enabled there should be no way to get around it. If there is it is an exploit and should be avoided.
|
6,191,508 | 6,191,625 | casting signed to unsigned | is it correct to do this?
typedef unsigned int Index;
enum
{
InvalidIndex = (Index) -1
};
I have read that it is unsafe across platforms, but I have seen this in so many "professional" codes...
| What you read was probably out of Fear, Uncertainty and Doubt. The author of whatever you read probably thought that (unsigned)-1 was underflowing and potentially causing chaos on systems where the bit representation doesn't happen to give you UINT_MAX for your trouble.
However, the author is wrong, because the standar... |
6,191,588 | 6,191,899 | Reciprocal friend member functions = circular include declarations | I have two classes defined in different h files and each class has some private functions. However, there's one function in each class that I want to be able to access from a function in the other class.
For example...
//apple.h:
class Beets;
class Apple
{
public:
double ShadeUsed();
private:
void Fruit(... | You could use friend functions which call the member functions.
//apple.h:
class Beets;
class Apple
{
public:
double ShadeUsed();
private:
void Fruit();
bool RedRoots();
friend bool Beets_BlueRoots(Beets* beets);
friend bool Apple_RedRoots(Apple* apple);
};
bool Apple_RedRoots(Apple* ap... |
6,191,678 | 6,191,800 | Print C++ vtables using GDB | I'm trying to print an object's vtable using gdb; I found the
show print vt bl on
setting, but I still don't actually know how to print the vtable - p *object still doesn't print it out.
How do I print the vtable?
|
(gdb) set $i = 0
(gdb) while $i < 10
>print $i
>p /a (*(void ***)obj)[$i]
>set $i = $i + 1
>end
Where "obj" is the object whose vtable you'd like to print, and 10 is the number of methods.
|
6,191,759 | 6,191,889 | Portably Compile Entire Directory | Is there a clean/portable way to descend recursively from a given directory, compiling all found .cpp files into a single output file? I'm not sure if makefiles are capable of this sort of thing, or if it's a job for some kind of build script, but I'd like to avoid maintaining various IDEs' project files along with my... | There are different things that you can do here. I would suggest that you use a multiplatform build system, and follow the documentation for it. I have used CMake in the past, but I wouldn't know how to tell it to compile all files in a directory.
The advantage is that the user can use CMake to generate project files ... |
6,191,772 | 6,194,392 | Calling C/C++ functions in dynamic and static libraries in D | I'm having trouble wrapping my head around how to interface with C/C++ libraries, both static (.lib/.a) and dynamic (.dll/.so), in D. From what I understand, it's possible to tell the DMD compiler to link with .lib files, and that you can convert .dll files to .lib with the implib tool that Digital Mars provides. In ad... | Note you are dealing with three phases for generating an executable. During compilation you are creating object files (.lib/.a are just archives of object files). Once these files are created you use a Linker to put all the pieces together. When dealing with dynamic libraries (.dll, .so) there is the extra step of load... |
6,191,879 | 6,191,979 | New is taking lots of extra memory | I'm making an application that is going to be using many dynamically created objects (raytracing). Instead of just using [new] over and over again, I thought I'd just make a simple memory system to speed things up. Its very simple at this point, as I don't need much.
My question is: when I run this test application, us... | There is a minimum size for a memory allocation, depending on the CRT you are using. Often that's 16 bytes. Your object is 12 bytes wide (assuming x86), so you're probably wasting at least 4 bytes per allocation right there. The memory manager also has it's own structures to keep track of what memory is free and what m... |
6,191,947 | 6,191,993 | What is the purpose of message handler INT_PTR return value? | I was playing with visual studio's windows forms and the example code had this:
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
/*code cut*/
case WM_INITDIALOG:
return (INT_PTR)TRUE;
break;
While my other handler function looks like this:
LRESULT CALLBACK WndProc(HWND ... | The first piece of code is a DialogProc -- quoting the relevant docs:
Return Value
Type: INT_PTR
Typically, the dialog box procedure should return TRUE if it processed the message, and FALSE if it did not. If the dialog box procedure returns FALSE, the dialog manager performs the default dialog operation in respon... |
6,192,011 | 6,192,513 | How to prevent iostreams::mapped_file_sink from creating executable txt files | EDIT: code sample is broken, it is missing .is_open(), please DON'T use it.
I have a rather strange question. I use boost iostreams and they work awesome, but the problem is that files that program creates are executable txt files(I'm on ubuntu,msg is :""lol2.txt" is an executable text file.").
So is there any way to... | You can change the file creation mask of your process to create non-executable files by default:
umask(getumask() & ~(S_IXUSR | S_IXGRP | S_IXOTH));
|
6,192,027 | 6,192,275 | Destructor Called Twice While No Copy Constructor or Assignment Operator Gets Callled | I have a class:
class A
{
public:
A()
{
std::cout << "Constructor called" << std::endl;
}
~A()
{
std::cout << "Destructor called" << std::endl;
}
A(const A& another)
{
std::cout << "Copy constructor called" << std::endl;
}
A& operator=(const A& another)... | If you are somehow calling the destructor twice, maybe you have two objects that think they own it through a pointer.
If you really do have two objects that think they own this one, consider using a reference counted pointer such as Boost::shared_ptr or tr1::shared_ptr to contain it. That way you don't have to worry ab... |
6,192,028 | 6,192,422 | casting member function pointer | I need to use a member function pointer that takes in an argument of base class that used in other code. Well, simply I want do to [something] like the example below. This code works fine, but I wonder if such cast is always safe? I cannot do dynamic or static cast here.
#include <cstdio> ... | What you are trying to do cannot be done legally in C++. C++ does not support any kind of co-variance or contra-variance on function parameter types, regardless of whether this is a member function or a free function.
In your situation the proper way to implement it is to introduce an intermediate function for paramete... |
6,192,230 | 6,192,272 | Help with macro functions | Given many inline functions with identical signatures. All functions are small and performance critical.
int inline f1(int);
int inline f2(int);
...
int inline f5(int);
I need to write high level functions to automate certain tasks - one high level function per each inline function. n-th high level function uses only ... | Why not use templates?
template <int N>
int inline f(int);
template <>
int inline f<1>(int);
template <>
int inline f<2>(int);
template <>
int inline f<3>(int);
...
template <int N>
int F(int x)
{
int y;
y = x * f<N>(x);
return y;
}
Edit: If it should work in C, use a macro like this:
#define GENERATE... |
6,192,418 | 6,192,657 | Message Box sending Windows messages? | I've got a relatively simple Window class. I've created a window, associated my this, etc etc. Now later, I've thrown an exception to indicate a problem. When I call MessageBox to pop up the error, the program crashes, because it's attempting to call my Window Proc. Now, I mean, admittedly, I failed SRP here and just w... | What is happening here is that there are still messages for the dud window in the queue when you show the message box. The message box runs a modal window message pump and dispatches the troublesome messages. Remember that all windows created from the same thread share a single message queue.
I have no idea how to fix ... |
6,192,483 | 6,192,535 | Doxygen comment inside a macro | My problem is the following : I have a set of files with the same parameters for constructors. I defined the parameters of a constructor inside a macro which is used in each file. For example, the following constructor :
Planar(BSPF_IMAGE_FORMAT_STD_CONST_PARAMS_3);
uses the BSPF_IMAGE_FORMAT_STD_CONST_PARAMS_3 macro ... | Macros are always expanded without a line break, this got nothing to do with doxygen. However, a solution is relativly simple:
Have an extra text-file ("BSPF_IMAGE_FORMAT_STD_CONST_PARAMS_3.txt" or similar) that contains the comment specific to that define, an extra
#define BSPF_IMAGE_FORMAT_STD_CONST_PARAMS_3_INCLUDE ... |
6,192,563 | 6,195,711 | Detect Windows (IE) proxy settings changes | I'm using WinHttpGetIEProxyConfigForCurrentUser and friends to gather the current proxy information when my app starts as doing it before each request seems to degrade performance greatly with it something sitting for a few seconds gathering the proxy data. Is there a way to detect when the Windows proxy settings have ... | Not sure if there is a better way, but you could always take the nuclear option and use RegNotifyChangeKeyValue with HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings.
|
6,192,628 | 6,192,767 | Thread safety and bit-field | I know that bit-field are compiler dependant, but I haven't find documentation about thread safety on bit-field with the latest g++ and Visual C++ 2010.
Does the operations on a bit-field member are atomic ?
| "Thread safe" is unfortunately a very overloaded term in programming.
If you mean atomic access to bit-fields, the answer is no (at least on all processors I'm aware of). You have atomic access to 32bit memory locations on 32bit machines, but that only means you'll read or write a whole 32 bit value. This does not mean... |
6,192,660 | 6,192,678 | Can I rely on template type? | I am looking into working code from Game AI by example book and there is a part I do not understand.
There is
template <class node_type, class edge_type>
class SparseGraph
{ ... };
and
int SparseGraph<node_type, edge_type>::AddNode(node_type node)
{
if (node.Index() < (int)m_Node... | If node_type is not GraphNode, then your compiler will smack you and throw an error. However, if your class depends on the Index function, then you should document it as a requirement and any replacement for GraphNode must provide it, probably with some expected semantics.
|
6,192,841 | 6,193,036 | Win API Local File Reference c++ | I am trying to hard code into C++ program to look for config.ini in the same directory as the executable, without knowing the complete path to the file. I am trying to find a way to make a local reference to the executable.
Basically load ("./config.ini")
without doing
("C:\foo\bar\config.ini")
| You want GetModuleFilename() on Windows (pass NULL to get filename of current executable). Otherwise, call boost::filesystem::initial_path() early in the program (see Boost docs in link for the reason to do this early). That should cover most of the situations.
Edit
Brain malfunction. We always start our programs fr... |
6,193,377 | 6,193,445 | How to get the length of a dialog item text? | Im trying to get the dialog item text into a buffer. It works with GetDlgItemText(), but how do i get the length of the text so i can allocate the buffer before i read it in there? I want to be sure i always get the whole text. I could use always for example 10k buffer, but it would be nicer if there wasnt any chance t... | Send the window handle, obtained by calling GetDlgItem, a WM_GETTEXTLENGTH message. Or if you prefer call GetWindowTextLength.
|
6,193,506 | 6,193,675 | VS 2010 C++ IntelliSense "a storage class may not be specified here" even though it can? | This is a fairly minor question, but it's annoying me: IntelliSense seems to be convinced that declaring static variables at the function-scope in an if condition is an error, and complains about it. Only it builds just fine, and even the MSDN docs mention it as a legitimate usage. I'd really like to get rid of the wav... | The VC++ compiler allows this as a silent extension (it is not legal C++), but the VC++ IntelliSense engine is based on the EDG compiler frontend, not the VC++ compiler (go figure). So, the IntelliSense error is correct if you're concerned about writing portable code.
|
6,193,734 | 6,194,078 | Implicit conversions with std::function |
Possible Duplicates:
Why can't my C++ compiler deduce template argument for boost function?
Isn't the template argument (the signature) of std::function part of its type?
I have the following:
#include <functional>
void Foo( std::function<void()> );
void Foo( std::function<void(int)> );
void Bar();
int main()
{... | Any call to Foo with a parameter which is not exactly one of std::function<void()> and std::function<void(int)> will result in an unresolved overloading. Even silly things like Foo(1) or Foo("abc"). This is because constructors of std::function are templated and accept any type. std::function<void()>(1) would fail at i... |
6,193,827 | 6,193,864 | Static variables and functions usage | I have the following class definition and the main(). Can someone please point me why I am getting the error?
#include <iostream>
#include <list>
using namespace std;
class test
{
protected:
static list<int> a;
public:
test()
{
a.push_back(150);
}
static void send(int c)
{
if (c==1)
cout<<a.f... | You've declared test::a, but you haven't defined it. Add the definition in namespace scope:
list<int> test::a;
|
6,193,889 | 6,193,933 | C++: Adding automatically allocated objects to a std::vector | I wrote the following code:
#include <iostream>
#include <vector>
using namespace std;
class AClass
{
public:
int data;
AClass()
{ data = -333; cout << "+ Creating default " << data << endl; }
AClass(const AClass ©)
{ data = copy.data; cout << "+ Creating copy of " <... |
It appears that vector is making copies of existing objects when new ones are added
When you add an element, e.g. with v.push_back(AClass(i));, what is done is a temporary AClass object is created and passed to push_back. push_back must then copy this object into the container.
The other reason that you see copies m... |
6,194,031 | 6,194,669 | Iterating Variadic Macro Arguments | I am programmatically generating bunch of functors, in order to keep the generated code more readable I am trying to come up with a macro that will expand line the following,
SET_STATE(FunctorA,a,b);
ref a;
ref b;
FunctorA(ref a, ref b){
this->a = a;
this->b = b;
}
Basically it will expand to the first argument... | Using the tricked found in this link http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/ to count the number of arguments and using some really ugly macro I can generate the output you wanted.
I tested it using gcc (gcc -E test.cpp) and it works, It's not portable.
Code:
#define VA_NARGS_IMPL... |
6,194,075 | 6,209,955 | How to close a file handle opened with SHCreateStreamOnFile | Since I need to format "pretty" XML using MSXML, I am using the trick referenced here to add indentation to my code. Since all I want is to save a file, I open an IStream using SHCreateStreamOnFile(). The file gets saved, I can open it in a text editor and the XML content is there. Then I call Release() on the IStream ... | ildjarn was right, I was passing it to an object that didn't get deleted, because I didn't knew that QueryInterface incremented the reference count ( I tought it was kind of a "COM" way of casting a pointer ). Releasing that object released the file at the same time.
A beginner mistake from someone not used to COM prog... |
6,194,490 | 6,194,515 | Memory leak in using a list of lists | I had some code thrown at me to 'productionize.' I ran a memory leak checker and it calls out the following line within the 'for' loop below as a memory leak.
someStruct->arrayMap = new std::list<BasisIndex>*[someStruct->mapSizeX];
for(int i=0; i<someStruct->mapSizeX; i++){
someStruct->arrayMap[i] = new std::list... | Deallocate the objects in the reverse order that you allocated them.
Allocation:
someStruct->arrayMap = new std::list<BasisIndex>*[someStruct->mapSizeX];
for(int i=0; i<someStruct->mapSizeX; i++){
someStruct->arrayMap[i] = new std::list<BasisIndex>[someStruct->mapSizeY];
}
Deallocation:
for (int i=0; i<someStruc... |
6,194,797 | 6,194,817 | What is a C++ container with a "contains" operation? | I want to use a structure in which I insert integers, and then can ask
if (container.contains(3)) { /**/ }
There has to be something like this.
| You can use std::vector.
std::vector<int> myVec;
myVec.push_back(3);
if (std::find(myVec.begin(), myVec.end(), 3) != myVec.end())
{
// do your stuff
}
You can even make a little helper function:
template <class T>
bool contains(const std::vector<T> &vec, const T &value)
{
return std::find(vec.begin(), vec.end(... |
6,194,914 | 20,758,743 | Death Testing a constructor with GoogleTest | Getting a seg fault while trying to ASSERT_EXIT object creation that throws a custom exception on bad parameters like so:
ASSERT_EXIT( MyObj(1,2,3) , ::testing::ExitedWithCode(1), "");
where the class being created is like so:
class MyObj
{
public:
MyObj(int a, int b, int c) { if( a < b ) throw MyException("Error"... | Please consider ASSERT_DEATH if you expect unhandled exception that must terminate your application (like throwing from nothrow member or call exit explicitely)
or ASSERT_THROW if you have normal exception
|
6,194,941 | 6,381,119 | Using output from gpg --list-packets on a key to get the mpi values to generate s-expressions | I am trying to use gpg generated public keys to do encryption using libgcrypt. I used the list packets command on the key to get me the contents of the key and parsed the mpi values into an s-expression. So when I try to encode my session key with my public key I get the error "Odd hexadecimal numbers in S-expression"?... | After trial and error and advice from the gpg and libgcrypt mailing lists, the list packets command does truncate the leading zeros from the mpi value and as a result you would have to pre-pend the mpi values with zero(s) when:
the length of the hex string is a odd number (pre-pend with one zero) or
the mpi is a negat... |
6,195,033 | 6,705,674 | STM32F103 microcontroller CAN messages | I am wondering if anyone is familiar with any STM32f10x micro-controllers?
If so, I am having some problems configuring a CAN driver. I can run the demo code, which is set to a loop_Back mode, but I cannot get Normal_Mode to work.
I read through all the data sheets, and everything is configured correctly except the INA... | You set the Tx pin as Out_PP, but it should be configured as Alternate Function instead. Below is my init code for CAN on an STM32F107. I copy-pasted and stripped it from an existing project so some stuff is not needed (like not all GPIOs need to be enabled). Also note I used the remap function to put the CAN Rx and Tx... |
6,195,124 | 6,195,137 | How can I use the template parameter of a class as the template parameter of a class member? | I'm trying to implement the following in C++:
template <class T>
class Inner
{
public:
Inner(T inData){data = inData;};
~Inner(void){};
T data;
};
template <class T>
class Outer
{
public:
Outer(Inner<T> in){inner = in;};
~Outer(void){};
Inner<T> inner;
};
int main(void)
{
Inner<int> in (... | The problem is that you don't have a default constructor for inner. When the compiler initializes the object it calls the default constructor of inner before the assignment.
EDIT:
It's probably a good idea to properly implement a copy constructor and instead initialize inner like so:
Outer(Inner<T> in) : inner(in) { ... |
6,195,936 | 6,195,996 | C++ Guess Number game crashing on other computers and infinite loop fix | // Guess my number
// My first text based game
// Created by USDlades
// http://www.USDgamedev.zxq.net
#include <cstdlib>
#include <ctime>
#include <string>
#include <iostream>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); // seed the random number generator
int guess;
i... | The "crash" is probably related to missing runtime libraries, which would result in an error message similar to
The application failed to initialize
properly [...]
...requiring your friend to install the missing runtime libraries, e.g.
http://www.microsoft.com/downloads/en/details.aspx?familyid=a5c84275-3b97-4ab7-... |
6,196,065 | 6,196,078 | How to erase elements in a map with the elements keys in a set? | I have a set stores the keys which I want to delete in a map.
I tried the code blow, but it didn't compile.
std::set<std::string> keys;
std::map<std::string, std::string> mymap;
....
for_each(keys.begin(), keys.end(), boost::bind(&std::map<std::string,
std::string>::era... | You cannot take the address of a Standard Library member function because the declarations of such member functions are unspecified (an implementation is permitted to add additional, optional parameters or add additional overloads to otherwise non-overloaded member functions, so long as the behavior is the same).
The e... |
6,196,108 | 6,196,118 | C++ assign element of a string to a new string | Im trying to assign a piece of a string, to a new string variable. Now Im pretty new so longer, but easier to understand explanations are the best for me. Anyways, how Im trying to do it is like this:
string test = "384239572";
string u = test[4];
The full code of what im trying to do is this:
#include <iostream>
#inc... | You can use one of the string constructors
string u(1,test[4]);
EDIT: The 1 indicates the number of times to repeat the character test[4]
In your code you are trying to assign a char to a string object.
|
6,196,125 | 6,196,174 | When returning an object, why put the creation+initialization and the return as two seperate statements instead of one? | Example:
Foo make_foo(int a1, int a2){
Foo f(a1,a2);
return f;
}
Having seen such functions several times, is it just a matter of coding style / preference or is there more to it than meets the eye? Specifically this answer got me thinking with the make_unique implementation and the claim it is exception safe - is... | Note that the answer to which you refer actually has something different:
std::unique_ptr<T> ret (new T(std::forward<Args>(args)...));
In this line of code, explicit dynamic allocation is performed. Best practices dictate that whenever you perform explicit dynamic allocation, you should immediately assign the result ... |
6,196,212 | 6,196,326 | How do you set a radiobutton as selected using code in gtk? | A radiobuttongroup was created and several radiomenuelems were created in that group.
Clicking them results in the expected effect, but how do you set a radiobutton using code?
I've searched google for the answer but I can only find other people asking the same question without an answer such as here: http://markmail.o... | You can use Gtk::CheckMenuItem::set_active assuming you are asking about gtkmm, or gtk_check_menu_item_set_active from plain old GTK.
|
6,196,305 | 6,196,356 | How to add simple debug to Application using preprocessor defines | I am developing a GUI app on WinXP but unfortunately std::cerr/cout goes nowhere. I would like to add a simple debug method that appends messages to a log file.
I have been hashing together an almost workable solution reading other posts. And am able to have a single debug() method call in my GUI app. However, don't... | Your define for logfile is messed up.
When your code is preprocessed you'll get:
std::ofstream logfile("log/debug.txt", std::ios::app); << "[" << __DATE__ << " " << __TIME__ \
<< "] " << __FILE__ << ":" << __LINE__ << " " << "Starting Program" << std::endl;
What you would need to do is something like this in a... |
6,196,415 | 6,196,468 | C++ Libraries for abstracting calls against MSSQLS2008 and SQLite? | What are some good options for rendering transparent the small but meaningful differences in parsing and syntax between these two databases? Ideally, I'd like a mature and established library. In generally, in C++, what are some solidly abstracted libraries for high-level data access that don't sacrifice performance?... | SOCI is a good library for this, it supports SQLite3 and also MSSQL through ODBC. It also has backends for PostgreSQL, MySQL and Oracle if you need to use any of those later on.
Using it results in idiomatic stream code, as shown in their documentation:
int id = ...;
string name;
int salary;
sql << "select name, salar... |
6,196,452 | 6,197,864 | C++ static library to be used in XCode | This is probably not a simple question so I am not looking for a definite answer but just some pointers to get me in the right direction.
I have absolutely no experience with C/C++ but have good knowledge of Objective-C. I also don't know much about different compilers and architectures so please be nice if I am talkin... | Static libraries contain binary code tailored for some specific operating system and platform. That means that it will use the OS to internally acquire memory (if it uses dynamic memory) or to perform any other OS specific operation (logging, output).
Even if the generated code was completely OS-agnostic (basic math c... |
6,196,738 | 6,198,138 | RichEdit's EM_AUTOURLDETECT message recognizes link, but I can't click it | I have a RichEdit control in a dialog box. The RichEdit control displays RTF text. EM_AUTOURLDETECT causes the RichEdit control to properly format and recognize the hyperlink. When the mouse hovers over the link, the pointer changes to a hand, but the browser doesn't launch once the link is clicked.
Am I missing some k... | You can try something like this:
case WM_NOTIFY:
switch (((LPNMHDR)lParam)->code)
{
case EN_LINK:
ENLINK * enLinkInfo = (ENLINK *)lParam;
if (enLinkInfo->msg == WM_LBUTTONUP)
{
// code which gets clicked URL using enLinkInfo->chrg and saves it in
... |
6,196,825 | 6,196,869 | Avoid grabbing nothing from string stream | I'm working on an assembler for a very basic ISA. Currently I'm implementing parser function and I'm using a string stream to grab words from lines. Here's an example of the assembly code:
; This program counts from 10 to 0
.ORIG x3000
LEA R0, TEN ; This instruction will be loaded into memory locati... | The stream's error flags only get set after the condition (such as reaching the end of the stream) has occurred.
Try replacing your loop condition with:
while(ss >> token)
{
// Push it onto the words vector
words.push_back(token);
// If all we got was nothing, it's an empty line
if(token == "")
{
... |
6,197,163 | 6,197,182 | types in object oriented programming | I'm confused about why classes are considered data types.
I understand that part of them is "data", and the other part is the methods. Why are they called data types?
Procedures in procedural programming languages, like C, hold one or more fundamental data types, sometimes. But they are not called data types.
| Given the definition at Wikipedia:
[...] a data type (or datatype) is a classification identifying one of various types of data, such as floating-point, integer, or Boolean, that determines the possible values for that type; the operations that can be done on values of that type; and the way values of that type can be... |
6,197,536 | 6,197,576 | How do sets differentiate between objects? | How does a set differentiate between objects in both Java and C++? Or do sets not differentiate them at all?
Take these for example:
C++
std::set<A> aset;
A a(1, 2); // Assume A has only two elements, and this constructor sets them both
aset.insert(a);
A a2(1, 2); // This would initialise a `A' object to the same value... | In C++ the set depends on operator<() being defined for the class A, or that you supply a comparison object providing strict weak ordering to the set.
|
6,198,045 | 6,198,086 | Why does my linked list code result in link errors? | I'm new to linklist, and i'm having a tough time with it. I'm trying to display some values that i've appended to the nodes, But i keep getting linkerror messages. Here is what I have so far.
LinkList.h
-
#ifndef LINKLIST_H
#define LINKLIST_H
class LinkList
{
private:
struct ListNode
... | You declared a LinkList constructor, and a destructor, but you did not define them:
LinkList::LinkList() : head(NULL)
{
}
LinkList::~LinkList()
{
// delete your memory here...
}
|
6,198,145 | 6,270,940 | Code::Blocks to XCode : importing a C++ with a GUI | I currently have a project, written in C++, it uses multiple libraries, including an sqlite and a wxWidgets library, it has a Graphical User Interface, made with Interface Builder.
This project was made with Code::Blocks.
What I now want to do, is import this whole project into XCode to make an .app file. I know about ... | Steps taken
wx-config --cppflags
wx-config --libs
Opening a new xcode project (cocoa)
Pasting the code written (all the classes, and the interface built)
Organizing the header search paths (including the output of libs)
Organizing the linking
Organizing the GCC other flags (including the output of cppflags here)
af... |
6,198,224 | 6,198,255 | How to refer to enclosing instance from C++ inner class? | In C++, an object refers to itself via this.
But how does an instance of an inner class refer to the instance of its enclosing class?
class Zoo
{
class Bear
{
void runAway()
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
??? /* I need a point... | Unlike Java, inner classes in C++ do not have an implicit reference to an instance of their enclosing class.
You can simulate this by passing an instance, there are two ways :
pass to the method :
class Zoo
{
class Bear
{
void runAway( Zoo & zoo)
{
EscapeService::helpEscapeFrom (
... |
6,198,501 | 6,198,542 | Generate unique pin numbers (6 digits) using current time and username + password? | I need to use current time because later on, another program will need to know when I generated the pin and whats the username and password.
Summary:
Username + password + current time = pin [6 digits]
Reverse, generated pin, I need to know which particular, and check if its already pass 1 minute.
I am not asking for... | 999999 minutes, gives ~694 days, ~1.9 years. So if you used all the entropy available just for recording the current time, you'd cycle the value in less than 2 years.
And things will be much worse if you want to include the username and password, and avoid easy guessing.
With 6 decimal digits, you can store about 19 b... |
6,198,549 | 6,198,783 | C++ .dll files what exactly can they be used for and how to create them | i have been doing some looking at dlls. what exactly are all the uses of dlls...can they be used to store graphics? im guessing the main way to use them is to store code...or am i wrong? how do you go about creating dlls(with source and graphics? if possible).
any help would be appreciated.
i am using Code::Blocks ide ... | You're right, DLLs are meant for holding execution code.
However they can be used to embed images, using resources in Visual C++ but I don't think it's possible with Code::Blocks.
To create a DLL with Code::Blocks, simply create a new project with template "Dynamic Link Library".
|
6,198,702 | 6,198,722 | functor call (additional characters) | I tried to build a minimal example:
struct Functor
{
void operator()(int& a)
{
a += 1;
}
void other(int& a)
{
a += 2;
}
};
template <typename foo>
class Class
{
public:
void function()
{
int a = 10;
foo()(a);
std::cout << a... | You're not calling it on a pure type. foo() invokes the constructor, and evaluates to a temporary foo object, on which you then invoke operator().
To do the equivalent with a "normal" member function, just do:
foo().other(a);
|
6,199,122 | 6,199,262 | WINSOCK - Setting a timeout for a connection attempt on a non existing IP? | I am developing a RTSP Source filter in C++, and I am using WINSOCK 2.0 - blocking socket.
When I create a blocking socket, I set its SO_RCVTIMEO to 3 secs like so:
int ReceiveTimeout = 3000;
int e = setsockopt(Socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&ReceiveTimeout, sizeof(int));
My filter tries to connect to IP_ADD... | Bite the bullet. The remote IP may not be running a PING server or PING may be blocked by some router, so it's no help. Can you not just wait the 10 sec and then make whatever error indication you use?
If you absolutely have to time out the attempted connection after 3 seconds, you can time it out yourself.
|
6,199,328 | 6,221,045 | Windows Mobile 6 answer multiple calls | I develop a Windows Mobile 6 application where I have to manage multiple calls, using c++ TAPI (from C# using PInvoke).
The application works fine for a single call, but I do not know how to manage when I have an incoming call and I want to answer the second incoming call.
For example: I answer the first call with line... | I found myself the solution:
The command placed for the call is still lineAnswer but before, out application must be the owner of the call, so a I use lineSetCallPrivilege with the Owner value.
|
6,199,462 | 7,750,598 | Why does Edit & Continue stop working | I have a large C++ project under VS2008, and use edit & continue quite a bit during debugging. However, sometimes after quite minor changes edit and continue simply stops working. Debug / apply code changes is greyed out. If I rebuild all, it tends to come back, but this takes ~30mins. It seems very sporadic, much ... | I've eventually moved onto VS2010, SP1, and I'm delighted to note that edit and continue works like a charm. Far better in my case than any previous versions and quite a bit faster. FWIW, I've also moved onto a 64bit Windows 7 box with 16gb of RAM, so can't say definitively whether the problem was resource / compiler... |
6,199,595 | 6,199,645 | Where is the tell() function defined? | Can you please tell me where the off_t tell(int fd) function is defined in Mac OS X? It's not in fcntl.h and not in unistd.h, where it is defined in UNIX... I can't use ftell() because the code I'm porting works with file descriptors.
I'm using GCC v4.2.1
| You should be able to use lseek instead, which offers the same functionality:
off_t tell(int fd)
{
return lseek(fd, 0, SEEK_CUR);
}
|
6,199,872 | 6,199,963 | Running C++ code alongside and interacting with Python | So my current project is mostly in Python, but I'm looking to rewrite the most computationally expensive portions in C++ to try and boost performance. Much of this I can achieve via simple functions loaded from DLL files, but not everything. I have a multidimensional array in Python that I want to perform operations ... | First and foremost, when you are working with multidimensional arrays in Python, you should really be using NumPy. Chances are that your program is already fast enough when you let NumPy do the number crunching (use Array arithmetic instead of Python for loops).
If this is not enough, consider writing parts of your pr... |
6,199,910 | 6,204,183 | visual c++ and C++ builder | Can C++builder compile any c++ source files.
I don't have a good knowledge in c++. but i have some experience in delphi.
I like to use c++ but confused which one to use
I know that cbuilder has vcl , easy to develop ,easy for delphi developer
But my problem is can it compile any c++ files (vc++ and other source files).... | You'll find C++ Builder very comfy coming from Delphi if you don't care about MFC or .NET via C++/CLI etc and just want native C++ then either will work for you. Visual Studio 2010 supports a lot of the new C++0x features which is pretty nice, although they don't have variadic templates yet. I'm not sure how much of ... |
6,200,073 | 6,200,147 | Is there an efficient way to 'enumerate' a namespace in C++? | Is there a way to programmatically enumerate a namespace and its members in C++?
I have a large C++ program which utilizes several namespaces. I am unfamiliar with the codebase, and would like to determine which functions/classes/variables are associated with which namespaces.
My current approach involves simply remov... | This is not possible in C++.
However, you can use external tools, such as Doxygen, that will create documentation (HTML, and other formats) that will list all the members of your namespaces.
|
6,200,076 | 6,200,117 | Can i access c++ or Java functions inside python | I am mainly using python for extensive algorithms operations. Now i have my webiste in Django.
I few libraries in c++ and few in Java which i don't have in python. Or you can say that i already have some c++ , Java files in which some algorithm is coded.
can i call those function or do some calculation in my djnago sit... | For C++, certainly. Either write a module that wraps the library, or use something like ctypes or SWIG.
For Java, you'd be best to move to Jython (and correspondingly use django-jython).
Note that using both C++ and Java from Python is not trivial.
|
6,200,158 | 6,200,232 | Is it possible to use STL copy function with map | I wonder if there is any trick to use copy with maps to copy the contents of map into an array. Because STL maps are by the combination of a key value and a mapped value an element of a map forms a key value pair. That prevents us to use standard algorithms like std::copy. For example following code gives error:
#inclu... | You could use std::transform instead:
template <typename T, typename U>
const U &extract_second(const std::pair<T,U> &p)
{
return p.second;
}
std::transform(test.begin(), test.end(), test_arr, extract_second<int,double>);
And as @Andre points out in a comment below, if you want a slightly more verbose overhead, y... |
6,200,375 | 6,200,644 | Calculating the mean for a set of numbers while neglecting outliers | First of all this is more of a math question than it is a coding one, so please be patient.
I am trying to figure out an algorithm to calculate the mean for a set of numbers. However I need to neglect any numbers that are not close to the majority of the results. Here is an example of what I am trying to do:
Lets say I... | What you could do is:
estimate the percentage of outliers in your data: about 25% (4/15) of the provided dataset,
compute the adequate quantiles: 8-quantiles for your dataset, so as to exclude the outliers,
estimate the mean between the first and the last quantile.
PS: Outliers constituting 25% of your dataset is a l... |
6,200,752 | 6,200,799 | C++ header-only template library | Looking at this project (http://www.savarese.com/software/libssrckdtree/) I found the definition "C++ header-only template library". At the moment I have basic C++ knowledge but would like to know what this exactly means and why this people use it on this project
| It means all the definitions of template (function template or class template) are in the headers only. There is no .cpp file. There are only .h files (or some other extensions such as .hpp or no extension at all like <vector>, string> etc)
C++ compilers require the definitions of templates to be present in the same fi... |
6,200,935 | 6,200,975 | what is wrong with this code.. regarding strncat | sorry i modified the code now:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
int i=0;
char** f=NULL;
char* ff=NULL;
ff="abcd";
f=( char**)malloc ((i + 1) * sizeof (char *)+5);
f[0]=ff;
// strcpy(f[0],ff); (this again giving same error)
strncat(f[0],"e... | you are setting f<-ff
ff points to the start of a constant char[] ("abcd")
and then you change the value of *f (which is exactly *ff) thus - access violation.
|
6,201,289 | 6,201,379 | Can WM_HOTKEY be used to simulate hotkey events? | In my program(C++, WinAPI), I wanted to simulate pressing some existing hotkeys set in other running programs. I know there is a SendInput function which simulates the keyboard input, but it seemed too much work as it needs to create a lot of structures for the keys.
I was trying use SendMessage or PostMessage with HW... | SendInput is the best answer, honestly. This is because in the message loop your calls to the traslateaccellerator will look at the message , and in that message theres a bit flag on LPARAM, indicating what other keys are pressed with that key. You dont want to have to fill out that bit flag yourself, but ..... just i... |
6,201,695 | 6,207,597 | Investigating a bad free() pointer reference | My program is crashing badly in an unitary test, due to a free() call to a bad pointer, with this error message:
*** glibc detected *** /home/user/main.out: free(): invalid pointer: 0x006d0065 ***
The code looks roughly like this:
// constructor is MyObj( const std::string & )
// and copies the string in its own std:... | Ok, finally nailed the bug down.
For those interested, it was a structure that wasn't zeroed in the constructor of the class using it.
The schema was like this:
MyObj ---> BaseClass ---> structure member not initialized
Since this structure holds some pointers to strings, the NULL-check was failing and I'd free a bad ... |
6,201,759 | 6,247,885 | What's the difference between WaitForMultipleObjects and boost::asio on multiple windows::basic_handle's? | I have a list of HANDLE's, controlled by a lot of different IO devices. What would be the (performance) difference between:
A call to WaitForMultipleObjects on all these handles
async_read on boost::windows::basic_handle's around all these handles
Is WaitForMultipleObjects O(n) time complex with n the amount of handl... | since it sounds like the main use you would derive from asio is the fact that it is built on top of IO completion ports (iocp for short). So, let's start with comparing iocp with WaitForMultipleObjects(). These two approaches are essentially the same as select vs. epoll on linux.
The main drawback of WaitForMultipleObj... |
6,201,779 | 6,201,995 | How do you add a new form to an existing c++ project? | I want to add a new form which loads at startup on an existing command line c++ project , how do i go about this ?
| right click on project->add->New Item->select UI under Visual c++
You have to compile your app as CLR, to use win forms. Then from your exe's startup code, instantiate this form's object and then use objDlg->ShowDialog(). Its pretty much same
And clr option may not be compatible with MTd and few others(?)
|
6,201,807 | 6,202,215 | Are static functions acceptable practice for certain things in c++? | Sometimes, for certain things like writing a line to a console, feels like something that should be globally accessible to all objects. Something like:
writeError("UNHANDLED EXCEPTION",someData);
Also things such as math functions feel this way too. But how do you draw the line when doing this sort of thing becomes ba... | Some people draw the line at the point where the non-member function needs to be a friend of one of its arguments, so they use a lot of free functions.
Some people draw the line at the point where the non-member function could reasonably be a member function of one of its arguments, even though it doesn't actually use ... |
6,201,863 | 6,202,039 | Using virtual inheritance on "final" classes in unfinished class hierarchies | Is there any harm or is it considered bad design to preemptively derive virtually classes in an unfinished class hierarchy that are currently "at the bottom" (i.e., the most derived)? Is there a good reason one would want to wait until there was actually a need for virtual inheritance (i.e., when someone decides to ex... | I would avoid virtual inheritance until actually needed. When you use virtual inheritance you are leaking part of the abstractions that you build on your class, and in particular how you initialize your base class, by forcing the call to the virtual base to the most derived type.
|
6,202,006 | 6,202,179 | Plotting financial data | I'm implementing some simple machine learning algorithms on some financial data in c++, and would like to be able to present this in a 'professionel' way to a potential customer.
Does anyone know a good framework for displaying financial charts?
Or is there a simple way to do something else like embed gnuplot in a qt ... | If your customer is in finance, speak to them on their terms. Financial people do things in Excel and Powerpoint. Write your data in comma-separated value format, import this into Excel, create some Excel plots, and pull this into a Powerpoint presentation.
You might think of Excel and Powerpoint as being beneath someo... |
6,202,021 | 6,202,320 | Detecting function object (functor) and lambda traits | How can I detect the return type and parameter types of nullary and unary function pointers, std::function objects, and functors (including lambdas)?
Boost's function_traits and functional traits don't quite get me there out of the box, but I'm open to supplementing or replacing them.
I could do something like this:
na... | It's not possible in the general case for functors, i.e. class types using operator(). This includes lambda objects, too. Consider a case where operator() is overloaded:
struct functor {
double
operator()(double) const;
int
operator()(int) const;
};
typedef function_traits<functor>::result_type result... |
6,202,299 | 6,202,697 | How to get combo-box display values using the Data field? | I have set the combo-box data to "first;second;third" in the resource editor, but when I compile the program, the combo-box is totally empty, I can't see there any items at all.
Also, how do I set which item is selected by default ? And how do I change the currently selected item programmatically ?
| Checkout this tutorial on Win32 Combo boxes: Introduction to Combo Boxes
If you are using MFC CComboBox class then you need to use the methods AddString() or InsertString() to add elements in the combo box list.
|
6,202,547 | 6,202,623 | Win32 - Get Main Wnd Handle of application | I have injected my dll into process.
How can I get Main window handle of host application?
| The host application may have multiple 'main windows'. To detect them, you could
Call GetCurrentProcessId to get the PID of the current process
Call EnumWindows to iterate over all toplevel windows of the desktop
For each window on the desktop, call GetWindowThreadProcessId to get the PID of the process which created... |
6,202,608 | 6,211,256 | How to define an optional entry point into custom Mac OS X framework / dynamic library? | In Windows there is a DllMain and DLL_PROCESS_ATTACH / DLL_PROCESS_DETACH flags, which allow to initialize / free resources after DLL is attached to a process... So how can I specify an entry point in case of OS X? As always, I can't find anything useful in Apple documentation :(
| Wouldn't that work?
__attribute__((constructor)) void DllMain()
{
// code
}
|
6,202,655 | 6,203,475 | Boost asio ConstBufferSequence - c++ Templates | I am hoping for some guidance regarding C++ templates. I have been using the boost::asio library for communication over TCP. Thus far, I have been using storage containers built into the boost::asio library. For instance:
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost:... | boost::asio::buffer returns objects implementing the ConstBufferSequence and MutableBufferSequence concepts; it doesn't expect you to implement them. The concrete types you're allowed to pass to buffer are listed here.
|
6,202,825 | 6,202,913 | Class Definition Instance Instantiation Question | I have a class imgmanager that allows me to load all my images exactly once, it's quite nice, and while prototyping I had all of my files in one place, so I didn't have to worry about cyclical definitions. However after separating all of my classes I have a problem.
My Header File
#ifndef IMAGEMANAGER_H
#define IMA... | Don't create object instances in headers.
Create your object instance in one source file.
If you need to access it across multiple Translation Units, put this in your header:
extern imgmanager imagemgr; // declaration
This will inform all code that can "see" the header that there exists a so-named object; but it will ... |
6,202,933 | 6,204,072 | C++ Array Intersection | Does anyone know if it's possible to turn this from O(m * n) to O(m + n)?
vector<int> theFirst;
vector<int> theSecond;
vector<int> theMatch;
theFirst.push_back( -2147483648 );
theFirst.push_back(2);
theFirst.push_back(44);
theFirst.push_back(1);
theFirst.push_back(22);
theFirst.push... | Put the contents of the first vector into a hash set, such as std::unordered_set. That is O(m). Scan the second vector, checking if the values are in the unordered_set and keeping a tally of those that are. That is n lookups of a hash structure, so O(n). So, O(m+n). If you have l elements in the overlap, you may count ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.