question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,895,377 | 2,908,849 | General advice about scaling on QGraphicsView/QGraphicsScene | In my project I am using QGraphicsView/QGraphicsScene stuff.
On my scene there will be regions that contains 2D graphics.
Region count will be limited(Lets say 20)
Users can choose to display one or more regions.
If user choose to display one region I am going to show one region on scene
If user choose to display n reg... | QGraphicsView::fitInView() should do what you want:
QRectF bounding;
foreach(QRectF r, selectedRegionRects) {
bounding |= r;
}
scene->fitInView(bounding, Qt::KeepAspectRatio);
|
2,895,529 | 2,895,558 | How to read input until the user enters ^X | I am creating an interpreter for my esolang, and I need the user to enter some text which then will be interpreted as an INTERCAL program. I want the user to enter text, which may contain any character including newlines, until the user presses ^X (Ctrl-X), like this:
Enter your code followed by ^X:
Bla
Blablabla
Bla^X... | ^X has ASCII code 24, try checking for that.
http://www.unix-manuals.com/refs/misc/ascii-table.html
|
2,895,614 | 2,895,676 | Do I need to use locking with integers in c++ threads | If I am accessing a single integer type (e.g. long, int, bool, etc...) in multiple threads, do I need to use a synchronisation mechanism such as a mutex to lock them. My understanding is that as atomic types, I don't need to lock access to a single thread, but I see a lot of code out there that does use locking. Prof... | You are never locking a value - you are locking an operation ON a value.
C & C++ do not explicitly mention threads or atomic operations - so operations that look like they could or should be atomic - are not guaranteed by the language specification to be atomic.
It would admittedly be a pretty deviant compiler that man... |
2,895,669 | 15,982,337 | How to use OPENGL API in wince 6.0 r3 platform builder | How to use the following interface in wince 6.0 r3 for implementing hardware acceleration for graphics in silverlight
IRenderer
ICustomSurface
ICustomGraphicsDevice
| You can find here a Guide how to implement the Hardware acceleration for Silverlight in WEC7.
http://msdn.microsoft.com/en-us/library/jj919286.aspx
(I recommend to use Windows Embedded 7 for Silverlight if possible, Microsoft did quite some improvements compared to wince 6.0 r3)
Alternative you can also use a module wh... |
2,895,964 | 2,895,995 | Ofstream writes empty file on linux | I have a program which writes its output using ofstream. Everything works perfectly fine on Windows when compiled with Visual Studio, but it only writes empty file on Linux when compiled with GCC.
ofstream out(path_out_cstr, ofstream::out);
if(out.bad()){
cout << "Could not write the file" << flush;
}
else{
cout << "... | Works for me, ubuntu g++-4.1.
Have you tried to execute strace ./test and see if there are write() calls over the file?
|
2,896,238 | 2,896,267 | Dereferencing deleted pointers always result in an Access Violation? | I have a very simple C++ code here:
char *s = new char[100];
strcpy(s, "HELLO");
delete [] s;
int n = strlen(s);
If I run this code from Visual C++ 2008 by pressing F5 (Start Debugging,) this always result in crash (Access Violation.) However, starting this executable outside the IDE, or using the IDE's Ctrl+F5 (Start... | Accessing memory through a deleted pointer is undefined behavior. You can't expect any reliable/repeatable behavior.
Most likely it "works" in the one case because the string is still "sitting there" in the now available memory -= but you cannot rely on that. VS fills memory with debug values to help force crashes to h... |
2,896,286 | 2,896,310 | whats the difference between dot operator and scope resolution operator | I just wanted to know the difference between . operator and :: operator?
| The former (dot, .) is used to access members of an object, the latter (double colon, ::) is used to access members of a namespace or a class.
Consider the following setup.
namespace ns {
struct type
{
int var;
};
}
In this case, to refer to the structure, which is a member of a namespace, you use ... |
2,896,600 | 2,896,627 | How to replace all occurrences of a character in string? | What is the effective way to replace all occurrences of a character with another character in std::string?
| std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.
#include <algorithm>
#include <string>
void some_func() {
std::string s = "example string";
std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
|
2,896,654 | 4,533,524 | Is there open-source java/c/c++ framework for pipes-and-filters paradigm? | I'm interested in open-source Java/C/C++ framework for pipes-and-filters (like described in that book) paradigm.
Can you recommend some?
EDIT: I'm looking for as much "pure" (or lightweight) frameworks as possible: frameworks which encourage programming in "pipes-and-filters" technique, without reliance on any standard... | I just discovered Spring integration framework. Looks like the sample of what I was asking for.
|
2,896,689 | 2,896,975 | dereferencing the null pointer | int* p = 0;
int* q = &*p;
Is this undefined behavior or not? I browsed some related questions, but this specific aspect didn't show up.
| The answer to this question is: it depends which language standard you are following :-).
In C90 and C++, this is not valid because you perform indirection on the null pointer (by doing *p), and doing so results in undefined behavior.
However, in C99, this is valid, well-formed, and well-defined. In C99, if the opera... |
2,897,067 | 3,097,849 | Sorting a string in array, making it sparsely populated | For example, say I have string like:
duck duck duck duck goose goose goose dog
And I want it to be as sparsely populated as possible, say in this case
duck goose duck goose dog duck goose duck
What sort of algorithm would you recommend? Snippets of code or general pointers would be useful, languages welcome Python, ... | If I understood correctly your definition of “sparse”, this function should be exactly what you want:
# python ≥ 2.5
import itertools, heapq
def make_sparse(sequence):
grouped= sorted(sequence)
item_counts= []
for item, item_seq in itertools.groupby(grouped):
count= max(enumerate(item_seq))[0] + 1
... |
2,897,167 | 2,897,174 | wchar to char in c++ | I have a Windows CE console application that's entry point looks like this
int _tmain(int argc, _TCHAR* argv[])
I want to check the contents of argv[1] for "-s" convert argv[2] into an integer. I am having trouble narrowing the arguments or accessing them to test.
I initially tried the following with little success... | It should be:
if (_tcscmp(argv[1], _T("-s")) == 0)
|
2,897,317 | 3,093,504 | writing XML with Xerces 3.0.1 and C++ on windows | i have the following function i wrote to create an XML file using Xerces 3.0.1, if i call this function with a filePath of "foo.xml" or "../foo.xml" it works great, but if i pass in "c:/foo.xml" then i get an exception on this line
XMLFormatTarget *formatTarget = new LocalFileFormatTarget(targetPath);
can someone expl... | Are you using Windows Vista? perhaps you don't have the necessary permissions?
See this question: Exception in two line Xerces program
|
2,897,560 | 2,897,702 | How to change the meaning of pointer access operator | This may be very obvious question, pardon me if so.
I have below code snippet out of my project,
#include <stdio.h>
class X
{
public:
int i;
X() : i(0) {};
};
int main(int argc,char *arv[])
{
X *ptr = new X[10];
unsigned index = 5;
cout<<ptr[index].i<<endl;
return 0;
}
Question
Can I change the me... | As Alex says, your 'subindexing' usage of [] would be totally nonobvious for anyone reading your code.
That said, you can define a class such as this:
template<class T>
class SubindexingList {
vector<T> data;
vector<int> subindexes;
public:
SubindexingList(int count) : data(count) { }
void set_subindexe... |
2,897,706 | 2,898,251 | can i braodcast a UDP package to part of a network? | i am trying to broadcast a UDP package using subnet.
i want to braodcast my package to 192.168.1.255 ?
can i do that ? and how using c++ ?
| If you're using C++, I'd recommend using the Boost ASIO package for networking. The only gotcha is to be sure to set the broadcast ability on your UDP socket via:
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);
The "Examples" section of the boost documentation should have plenty of referen... |
2,897,907 | 2,897,945 | How to simulate a file read error in the CRT | Using VS2008, we would like to simulate a file that has a size of X, but that has a read failure at X-Y bytes, so that we get an error indication.
Anyone have an idea of how to do this on windows? Looks like there is a solution for linux, but I can't really come up with a way to do this on windows. We have multiple de... | Wrap the file I/O functions in a class; override those in a testing derived class; simulate failure with a fake or mock.
|
2,897,921 | 2,898,002 | How to use openssl crypto lib headers in C++? | I am trying to test the crypto library that comes with openssl, I downloaded openssl from http://www.openssl.org/source/ and it contains a /crypto folder with subfolders for each encryption type.
I wanted to try BIO_f_base64 so I created an empty console app, and added the includes needed, also added the paths to the /... | You need a version of the OpenSSL that is built for Windows, not the source release. I recommend installing a version from here, which has some nice installers for .lib files and headers. Once you have it installed you will have to update your VS project with the proper include paths to pick up the headers from where... |
2,897,936 | 2,899,879 | Is it possible to have an out-of-process COM server where a separate O/S process is used for each object instance? | I have a legacy C++ "solution engine" that I have already wrapped as an in-process COM object for use by client applications that only require a single "solution engine".
However I now have a client application that requires multiple "solution engines". Unfortunately the underlying legacy code has enough global data, s... | Yes, this is possible. The key is to register your coclass by calling CoRegisterClassObject, and OR-in the value REGCLS_SINGLEUSE in the flags parameter.
If your project is an ATL 7.0+ project, you can do this by overriding CAtlExeModuleT::PreMessageLoop(), which is responsible for registering the class object, thusly... |
2,898,094 | 2,898,310 | Why C++ virtual function defined in header may not be compiled and linked in vtable? | Situation is following. I have shared library, which contains class definition -
QueueClass : IClassInterface
{
virtual void LOL() { do some magic}
}
My shared library initialize class member
QueueClass *globalMember = new QueueClass();
My share library export C function which returns pointer to globalMember -
vo... | The linker is the culprit here. When a function is inline it has multiple definitions, one in each cpp file where it is referenced. If your code never references the function it is never generated.
However, the vtable layout is determined at compile time with the class definition. The compiler can easily tell that t... |
2,898,155 | 2,898,186 | Is rand() predictable in C++ |
Possible Duplicate:
What’s the Right Way to use the rand() Function in C++?
When I run the below program I always get the same values each time. Is rand not a true random function?
int main()
{
while(1)
{
getch();
cout<<rand()<<endl;
}
}
In each run I am getting the below values.
41
18467
6334
26500
19169
... | Yes and no. rand() is a pseudo random number generator that will always return the same sequence of numbers given the same seed value. Typically one 'seeds' the random number generator with some random data and then uses rand() to return a sequence of seemingly random numbers. If your random data isn't needed for somet... |
2,898,316 | 2,898,328 | Using a member function pointer within a class | Given an example class:
class Fred
{
public:
Fred()
{
func = &Fred::fa;
}
void run()
{
int foo, bar;
*func(foo,bar);
}
double fa(int x, int y);
double fb(int x, int y);
private:
double (Fred::*func)(int x, int y);
};
I get a compiler error at the line calling the member function through the pointer "... | The syntax you need looks like:
((object).*(ptrToMember))
So your call would be:
((*this).*(func))(foo, bar);
I believe an alternate syntax would be:
(this->*func)(foo, bar);
|
2,898,590 | 2,898,597 | How to see c++ and c# dll dependencies? | I have a python project that calls a c++ wrapper dll that calls a c# com interop dll.
In my computer, with all frameworks and programs installed, my project runs very well.
But in a computer that just got formatted it doesn't.
I allready installed c++ 2008 redistribute and the c++ part is working but when I call a func... | Looks like you need Dependency Walker.
|
2,898,758 | 2,900,125 | ptr to c++ source for a simple mac (cocoa) based console to use as a command interpreter | I have the command language part sorted out, I'm looking for good sample on how to build a custom console in Cocoa. Need features like copy/paste, command stack, ctrl-z processsing etc. Thanks in advance.
| There's the open source iTerm console application, that might give you the example you want.
|
2,898,870 | 2,899,689 | Suggestions on syntax to express mathematical formula concisely | I am developing functional domain specific embedded language within C++ to translate formulas into working code as concisely and accurately as possible.
I posted a prototype in the comments, it is about two hundred lines long.
Right now my language looks something like this (well, actually is going to look like):
// im... | If you're going to be writing this for the ab-initio world (which I'm guessing from your MP2 equation) you want to make it very easy and clear to express things as close to the mathematical definition that you can.
For one, I wouldn't have the complicated range function. Have it define a loop, but if you want nested l... |
2,899,013 | 2,899,042 | How do I get the application data path in Windows using C++? | I looked all over the internet and there doesn't seem to be a decent solution that I could find. I want to be able to programmatically in C++ obtain the path "%ALLUSERSPROFILE%\Application Data" that explorer can translate into a real path.
Can I do this without relying on third-party code?
| Use SHGetFolderPath with CSIDL_COMMON_APPDATA as the CSIDL.
TCHAR szPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath)))
{
//....
}
|
2,899,207 | 2,899,333 | Implementing Dijkstra's Algorithm | I've been tasked (coursework @ university) to implement a form of path-finding. Now, in-spec, I could just implement a brute force, since there's a limit on the number of nodes to search (begin, two in the middle, end), but I want to re-use this code and came to implement Dijkstra's algorithm.
I've seen the pseudo on W... | Here's a high level breakdown of Dijkstra's algorithm:
You stick all of the vertices in a priority queue where all of the vertices have a priority (distance) of infinity except for the source vertex, which has a distance of zero (the source vertex is zero units of distance away from itself, right?).
Pop the priority qu... |
2,899,511 | 2,899,546 | Should I call class destructor in this code? | I am using this sample to decode/encode some data I am retrieving/sending from/to a web server, and I want to use it like this:
BOOL HandleMessage(UINT uMsg,WPARAM wParam,LPARAM lParam,LRESULT* r)
{
if(uMsg == WM_DESTROY)
{
PostQuitMessage(0);
return TRUE;
}
else if(uMsg == WM_CREATE)
{
// Start t... | base64 is in local storage. It goes out of scope and is destructed at the end of the block. The only question left is ownership of temp. If its memory is owned by base64, then you do not need to delete anything.
|
2,899,604 | 2,899,848 | Using sem_t in a Qt Project | I'm working on a simulation in Qt (C++), and would like to make use of a Semaphore wrapper class I made for the sem_t type.
Although I am including semaphore.h in my wrapper class, running qmake provides the following error:
'sem_t does not name a type'
I believe this is a library/linking error, since I can compile the... | I was able to compile and link your semaphore class using qmake without any unexpected steps (including linking in the rt or pthread libraries). I created the following main:
#include "Semaphore.h"
int main(int argc, char* argv[])
{
Semaphore sem;
return 0;
}
And then I generated the following projec... |
2,899,634 | 2,899,667 | event handling in C++ | I'm writing a game in C++, and I'm trying to get it to recognize keyboard and mouse events. Google tells me that boost.signal is suitable for event handling, but none of the code samples or tutorials I've found tell me how to associate a keypress or mouseclick with a function. Can anyone shed any light on this?
| I think taking a look at SDL and it's SDL input subsystem might give you some hints. It all depends on what is the source of your keyboard and mouse events. Is it SDL? DirectX? If neither, then you're probably doing it wrong :).
|
2,899,655 | 4,646,999 | BitBlt ignores CAPTUREBLT and seems to always capture a cached copy of the target | I am trying to capture screenshots using the BitBlt function. However, every single time I capture a screenshot, the non-client area NEVER changes no matter what I do. It's as if it's getting some cached copy of it. The client area is captured correctly.
If I close and then re-open the window, and take a screenshot, th... | Your confusion about BitBlt with CAPTUREBLT behaviour comes from the fact that official BitBlt documentation is unclear and misleading.
It states that
"CAPTUREBLT -- Includes any windows that are layered on top of your window in the resulting image. By default, the image only contains your window."
What actually means ... |
2,899,675 | 2,984,126 | getElementsByTagName returns 0-length list when called from didFinishLoad delegate | I'm using the Chromium port of WebKit on Windows and I'm trying to retrieve a list of all of the images in my document. I figured the best way to do this was to implement WebKit::WebFrameClient::didFinishLoading like so:
WebNodeList list = document->getElementsByTagName(L"img");
for (size_t i = 0; i < list.length(); +... | It turns out that the mistake was purely on my side. I was caching a pointer to the DOM document in my frame wrapper. Of course, since a frame can outlive a DOM document, I ended up referencing an out-of-date document once I loaded a new page.
|
2,899,723 | 2,899,757 | C++ hook process and show status | Ok so I am learning C++ slowly. I am familiar with all the console syntax and everything, but now I'm moving on to windows programming. Now what im trying to do, is create a DLL that I inject into a process, so it's hooked in. All I want the C++ application to do, is have text in it, that says "Hooked" if it's successf... | I think you might be looking at this backwards. In C/C++ an application 'pulls' a DLL in rather than having a DLL 'injected' into an application. Typically for plugins/hooks, there is some mechanism to inform an application of a DLL's availability (often just its presence in a specific directory) and a configuration fi... |
2,899,764 | 2,900,190 | How can one make a 'passthru' function in C++ using macros or metaprogramming? | So I have a series of global functions, say:
foo_f1(int a, int b, char *c);
foo_f2(int a);
foo_f3(char *a);
I want to make a C++ wrapper around these, something like:
MyFoo::f1(int a, int b, char* c);
MyFoo::f2(int a);
MyFoo::f3(char* a);
There's about 40 functions like this, 35 of them I just want to pass through t... | You could use Boost.Preprocessor to let the following:
struct X {
PASSTHRU(foo, void, (int)(char))
};
... expand to:
struct X {
void foo ( int arg0 , char arg1 ) { return ::foo ( arg0 , arg1 ); }
};
... using these macros:
#define DO_MAKE_ARGS(r, data, i, type) \
BOOST_PP_COMMA_IF(i) type arg##i
#define PA... |
2,899,803 | 2,903,075 | Monochrome BitMap Library | I am trying to create a piece of software that can be used to create VERY large (10000x10000) sized bitmaps. All I need is something that can work in monochrome, since the required output is a matrix containing details of black and white pixels in the bitmap. The closest thing I can think of is a font editor, but the s... | Why don't you use bitmap objects, like gdk pixmaps if you use GTK?
10,000 x 10,000 pixels with a depth of 1 (monochrome) is 100,000,000 bits, which is 12,500,000 bytes, around 12 megabytes.
Not that large.
|
2,900,244 | 2,900,368 | Is this usage of test_and_set thread safe? | I've been thinking of how to implement a lock-free singly linked list. And to be honest, I don't see many bullet proof ways to do it. Even the more robust ways out there that use CAS end up having some degree of the ABA problem.
So I got to thinking. Wouldn't a partially lock-free system be better than always using loc... | You're correct. In C++, the arguments to a function are evaluated in any order, but certainly your compiler has no way of knowing that root->next is an atomic operation in your sequence.
Consider two threads calling pop(): One thread evaluates root->next, then the other evaluates root->next, and both call test_and_set(... |
2,900,357 | 2,900,523 | Producer/Consumer Implementation -- Feedback Wanted | I'm preparing for an interview in a few weeks and I thougth I would give threads in boost a go, as well as do the simple producer/consumer problem I learned in school.
Haven't done it quite awhile so I was curious what you guys think of this? What should I add to make it a better example etc. Thanks for the feedback! :... | If you are already wrapping your buffer object in calls like AddToBuffer and GetFromBuffer, it would make more sense for you to put the locking within your wrapper functions. In addition, you are making an explicit call to unlock, which completely defeats the purpose of scoped_lock; scoped_lock uses Resource Acquisitio... |
2,900,392 | 2,900,574 | Truncate C++ string fields generated by ostringstream, iomanip:setw | In C++ I need string representations of integers with leading zeroes, where the representation has 8 digits and no more than 8 digits, truncating digits on the right side if necessary. I thought I could do this using just ostringstream and iomanip.setw(), like this:
int num_1 = 3000;
ostringstream out_target;
out_tar... | I can't think of any way to truncate a numeric field like that. Perhaps it has not been implemented because it would change the value.
ostream::write() allows you to truncate a string buffer simply enough, as in this example...
int num_2 = 2000000000;
ostringstream out_target;
out_target << setw(8) << setf... |
2,900,512 | 2,900,537 | Ctypes "symbol not found" for dynamic library in OSX | I have made a C++ library and have built a .dylib dynamic library from it. However when I load it with ctypes, it fails. Something doesn't seem to have linked properly. I have no idea why. The error (The relevant part):
cscalelib.setup_framebuffer(flip,surface.frame_buffer,surface.texture,surface._scale[0],surface.... | The problem is most likely the fact that you are using C++, and hence the function name will be mangled and use C++ calling conventions. If you declare the function with extern "C" then it should be exported in such a way as to callable from C code (and from Python's CTypes module).
|
2,900,531 | 2,900,561 | Help with memory leak (malloc) | I'v followed a tutorial to use OGL tesselaton. In one of the callbacks there is a malloc and it creates a leak every time I render a new frame.
void CALLBACK combineCallback(GLdouble coords[3], GLdouble *vertex_data[4],
GLfloat weight[4], GLdouble **dataOut)
{
GLdouble *vertex;
ve... | You should call free on whatever dataOut points to. For example, if you did this from the calling function:
combineCallback (coords, vertex_data, weight, &dataOut);
then you should call free (dataOut) after you're done using it later. If you free (vertex), that effectively means whatever dataOut points to is free to... |
2,900,729 | 2,901,007 | C++ templated factory constructor/de-serialization | I was looking at the boost serialization library, and the intrusive way to provide support for serialization is to define a member function with signature (simplifying):
class ToBeSerialized {
public:
//Define this to support serialization
//Notice not virtual function!
template<class Archive>
void seri... | All you need is to store some sort of identifier before storing the information from the derived type. Then upon reading you use that identifier, which you've read first, to direct you to a factory that can then interpret the next block of information correctly and generate your derived type. This is probably what bo... |
2,900,785 | 2,900,792 | What's the difference between cstdlib and stdlib.h? | When writing C++ code is there any difference between:
#include <cstdlib>
and
#include <stdlib.h>
other than the former being mostly contained within the std:: namespace?
Is there any reason other than coding standards and style to use one over the other?
| The first one is a C++ header and the second is a C header. Since the first uses a namespace, that would seem to be preferable.
|
2,900,862 | 2,900,890 | sort an array of floats in c++ | I have an array of (4) floating point numbers and need to sort the array in descending order. I'm quite new to c++, and was wondering what would be the best way to do this?
Thanks.
| Use std::sort with a non-default comparator:
float data[SIZE];
data[0] = ...;
...
std::sort(data, data + size, std::greater<float>());
|
2,901,152 | 2,901,178 | What is the purpose of the garbage (files) that Qt Creator auto-generates and how can I tame them? | I'm fairly new to Qt, and I'm using the new Nokia Qt SDK beta and I'm working to develop a small application for my Nokia N900 in my free time. Fortunately, I was able to set up everything correctly, and also to run my app on the device.
I've learned C++ in school, so I thought it won't be so difficult. I use Qt Creato... | Not a fully answer to your question, but just part of it :) Also, it's googlable.
Guess that if you develop in C++, you should know what does Makefile stand for. Also I think the .loc file is generally a file with localized strings / content.
(source: thelins.se)
Comparing the C++ build system to the Qt build system,... |
2,901,186 | 2,905,653 | SQL Server Native Client API examples | I am writing a C++ application that needs to execute SQL queries in a SQL Server DB and I want to do it using SQL Server Native Client.
The MSDN documentation has no a full reference on it and has a few examples so I am looking for some site having more information on how to connect, execute queries and retrieve result... | In addition to ODBC as Brian mentions, you can also use OLE DB and/or ADO (which actually makes OLE DB "easy" to use). The three options are briefly introduced in this blog entry.
Of the ODBC, OLE DB and ADO options, I think the simplest route would be to use ADO. Using ODBC or OLE DB directly is, in my opinion, a so... |
2,901,305 | 2,901,339 | Why doesn't this work? | I'v tried to solve a memory leak in the GLU callback by creating a global variable but now it dos not draw anything:
GLdouble *gluptr = NULL;
void CALLBACK combineCallback(GLdouble coords[3], GLdouble *vertex_data[4],
GLfloat weight[4], GLdouble **dataOut)
{
GLdouble *vertex;
if(g... | You allocate the data only once -- but GLUtesselator needs more than one set of data at a time!
What you do here, is putting all the vertex data into a single place in memory, where in the original code, you had memory per vertex. GLUtesselator needs more then one vertex to function properly.
You do call
void gluDelet... |
2,901,327 | 2,901,366 | Protecting an Application's Memory From Tampering | We are adding AES 256 bit encryption to our server and client applications for encrypting the TCP/IP traffic containing sensitive information. We will be rotating the keys daily. Because of that, the keys will be stored in memory with the applications.
Key distribution process:
Each server and client will have a list... | I think that you may have a more fundamental problem on your hands.
If there is even the faintest chance that this machine might catch a rootkit, then your all of your keys are ours, as it were.
On Windows, Process A can read the memory of Process B if any of the below are true:
it has privileges to open the memory d... |
2,901,556 | 2,901,638 | How to multi-thread this? | I wish to have two threads. The first thread1 occasionally calls the following pseudo function:
void waitForThread2() {
if (thread2 is not idle) {
return;
}
notifyThread2IamReady(); // i.e. via 1st condition variable
Wait for thread2 to finish exclusive access. // i.e. via 2nd condition variable.
}
The se... | I looks to me like you are trying to do a rendezvous (a term from Ada).
The second thread is sitting, waiting for the first thread to call it, then it does some work immediately while the first thread waits, and some more work after the first thread is finished.
The first thread is "calling" the second thread - with an... |
2,901,590 | 2,901,621 | Cannot run an executable binary file on another Linux System? | I'm using Ubuntu 10.04 and Qt4.6, and I've created an executable binary file on my own computer through QtCreator.
Now I want to put my executable file on CentOS 5, but it seems that this executable file cannot run on CentOS.
The error message is
bash: ./[filename]: cannot execute binary file
Now I know this comes fr... | Check 64-bit vs. 32-bit - file(1) is your friend here. Then check what libraries are missing with ldd(1).
Edit:
Take a look at this SO question Qt static linking and deployment.
|
2,901,738 | 2,901,762 | How do bezier handles work? | On Wikipedia I found information about bezier curves and made a function to generate the inbetween points for a bezier polygon. I noticed that Expression Design uses bezier handles. This allows a circle to be made with 4 points each with a bezier handle.
I'm just not sure mathematically how this works in relation with... | Basically, the 4 points used in the cubic bezier formula are the 2 points the curve is between, plus the two points of the handles on that "side" of the first two points (1 handle from each of the first points). If there are double handles on each point, the handles on the "opposite" side of the points from the curve c... |
2,902,186 | 2,902,277 | pass fortran 77 function to C/C++ | Is it possible to pass fortran 77 function as a callback function pointer to C/C++?
if so, how?
information I found on the web relates to fortran 90 and above, but my legacy code base is in 77.
many thanks
| If it can be done in FORTRAN 77, it will be compiler and platform specific. The new ISO C Binding of Fortran 2003 provides a standard way of mixing Fortran and C, and any language that follows or can follow the calling conventions of C, such as C++. While formally a part of Fortran 2003, and while there are extremely... |
2,902,511 | 2,902,820 | C++ double division by 0.0 versus DBL_MIN | When finding the inverse square root of a double, is it better to clamp invalid non-positive inputs at 0.0 or MIN_DBL? (In my example below double b may end up being negative due to floating point rounding errors and because the laws of physics are slightly slightly fudged in the game.)
Both division by 0.0 and MIN_DB... | When dealing with floating point math, "infinity" and "effectively infinity" are quite different. Once a number stops being finite, it tends to stay that way. So while the value of lorentz_factor is "effectively" the same for both methods, depending on how you use that value, later computations can be radically differ... |
2,902,717 | 2,902,768 | C++: Is there a way to limit access to certain methods to certain classes without exposing other private members? | I have a class with a protected method Zig::punt() and I only want it to be accessible to the class "Avocado". In C++, you'll normally do this using the "friend Avocado" specifier, but this will cause all of the other variables to become accessible to "Avocado" class; I don't want this because this breaks encapsulation... | Here's an ugly yet working trick:
class AvocadoFriender {
protected:
virtual void punt() = 0;
friend class Avocado;
}
class Zig : public AvocadoFriender {
...
protected:
void punt();
}
Basically you add a mixin class that exposes only the part of the interface that you want to Avocado. We take advantage of t... |
2,902,749 | 2,903,128 | Singleton class issue in Qt | i created a singleton class and trying to access that class in other class but getting error
"cannot access private member"
Setupconfig is my singleton class and i am trying to access this class in other class which have QMainWindow
And here is the error message:
Error 'Setupconfig::Setupconfig' : cannot access pri... | Why are you deriving "EasyBudget" from the singleton class "SetupConfig"?
Remove that part to resolve your problem.
EasyBudget.h
class EasyBudget : public QMainWindow, public Ui::EasyBudgetClass
{......
|
2,902,752 | 2,907,986 | Best way to have common class shared by both C++ and Ruby? | I am currently working on a project where a team of us are designing a game, all of us are proficient in ruby and some (but not all) of us are proficient in c++.
Initially we made the backend in ruby but we ported it to c++ for more speed. The c++ port of the backend has exactly the same features and algorithms as the ... | For creating ruby extensions you also might want to have a look at:
Rice
RubyInline
|
2,902,917 | 2,902,943 | static assert for const variables? | Static asserts are very convenient for checking things in compile time. A simple static assert idiom looks like this:
template<bool> struct StaticAssert;
template<> struct StaticAssert<true> {};
#define STATIC_ASSERT(condition) do { StaticAssert<(condition)>(); } while(0)
This is good for stuff like
STATIC_ASSERT(siz... | Why, you can still static assert with const int:
#define static_assert(e) extern char (*ct_assert(void)) [sizeof(char[1 - 2*!(e)])]
static_assert( THIS_LIMIT > OTHER_LIMIT )
Also, use boost!
BOOST_STATIC_ASSERT( THIS_LIMIT > OTHER_LIMIT )
... you'll get a lot nicer error messages...
|
2,902,976 | 2,903,018 | Programming Language to manipulate an Access Database | By quote, what is the appropiate language to manipulate an Access database?
A Windows user interface to manipulate
an existing Access Database.
... and why?
| Visual Basic .NET or C# would be my choice as there are enough objects and classes built-in to support create medium size database driven applications without writing much code :)
objects in the OleDb namespace can be used to connect and insert/retrieve/update data in the database
Here is a C# tutorial
http://msdn.mic... |
2,903,144 | 2,909,765 | How to set input focus to a shown dialog in Qt? | In a button click slot, I create and exec() a dialog with a NULL parent. Inside the dialog's constructor, I have:
this->activateWindow();
this->raise();
this->setFocus();
The dialog is application modal and has strong focus. However, it does NOT respond to keyboard events until I click on it. How do I make the dialog ... | The problem was that I was setting the Qt:Tool window flag. Using Qt::Popup or Qt::Window instead will cause input focus is automatically set when the dialog is shown.
I used Qt::Window myself. Some of the other flags will probably work as well, but the main thing is that a QDialog with the Qt::Tool flag will not autom... |
2,903,162 | 2,903,223 | Reading from istream | How can I extract data (contents) from istream without using operator>>() ?.
| If you want to read characters from the istream, then by using get and getline:
std::istream::get
std::istream::getline
For general reading you may want to use read:
std::istream::read
|
2,903,179 | 39,926,700 | intrusive_ptr: Why isn't a common base class provided? | boost::intrusive_ptr requires intrusive_ptr_add_ref and intrusive_ptr_release to be defined. Why isn't a base class provided which will do this? There is an example here: http://lists.boost.org/Archives/boost/2004/06/66957.php, but the poster says "I don't necessarily think this is a good idea". Why not?
Update: I don'... | Boost provides a facility for that. It can be configured for either thread-safe or thread-unsafe refcounting:
#include <boost/intrusive_ptr.hpp>
#include <boost/smart_ptr/intrusive_ref_counter.hpp>
class CMyClass
: public boost::intrusive_ref_counter<
CMyClass,
... |
2,903,360 | 2,903,388 | How to check whether a file exists in C:\ drive using VC++? | I want to check a file is present in C drive or not..? can any one tell me how ?
Update:
I got errors, I am using VC++ 2008
#include "stdafx.h"
#include <stdio.h>
int main(int argc, _TCHAR argv[])
{
FILE * f = fopen("C:\\Program Files (x86)\\flower.jpeg");
if (f == NULL) {
file_exists = FALSE:
... | Given you mention C drive, I'm assuming you can use the Windows API, if so PathFileExists(LPCTSTR) will do you
|
2,903,394 | 2,903,413 | How to compare two vectors, in C++ | This is my code:
#include <algorithm>
void f() {
int[] a = {1, 2, 3, 4};
int[] b = {1, 2, 100, 101};
// I want to do something like this:
// int* found = compare(a[0], a[3], b[0]);
// in order to get a pointer to a[2]
}
Maybe I missed this algorithm in the manual… Please help :)
| Sort your array and use mismatch.
|
2,903,427 | 2,903,498 | plug-in architecture based c/c++ application | I need to know how to start writing an application based on plug-in architecture. I mean how to write a base code and let others develop the application by adding the plug-ins they write.
I know that there is some problems in doing so in c++. most people use another language such as python to add plug-ins to their c++ ... | I think, this is not the answer you expect, but you could try to examine the Rainmeter sources. It's written in C++ (some places could be done better, to my mind, but overall it's ok) and the whole application is done the way so it just handles plugins.
Even the simple API is done via plugins, there is also a bunch of ... |
2,903,629 | 2,903,658 | Why doesn't this inner class compile? | This is my code:
#include <algorithm>
class A {
void f() {
struct CompareMe {
bool operator() (int i, int j) { return i < j; }
} comp;
int a[] = {1, 2, 3, 4};
int found = std::min_element(a[0], a[3], comp);
}
}
Error message:
no matching function for call to ‘min_element(int&, int&, A::f()::... | The error has nothing to do with your inner class. STL algorithms work on iterators. An iterator into an array of ints is a int*. The second of those iterators must always point to one passed the last element of the range.
This
int* found = std::min_element(&a[0], &a[4], comp);
works fine for me.
However, as far as... |
2,903,804 | 2,903,824 | can't compile min_element in c++ | This is my code:
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class A {
struct CompareMe {
bool operator() (const string*& s1, const string*& s2) const { return true; }
};
void f() {
CompareMe comp;
vector<string*> v;
min_element(v.begin(), v.end(), comp);
}
};
... | Your placement of const is wrong. A T*& cannot be implicitly converted to a const T*&. Try
bool operator() (const string* const& s1, const string* const& s2) const { ...
// ^^^^^ ^^^^^
instead.
Or just pass by value (thanks Mike):
bool operator() (const string* s1, const... |
2,903,882 | 2,903,915 | c++: strange syntax in what() method of std::exception | When i am inheriting from std::exception in order to define my own exception type, i need to override the what() method, which has the following signature:
virtual const char* what() const throw();
This definitely looks strange to me, like if there were two method names in the signature. Is this some very specific syn... | It is called exception specifications. The throw() doesn't allow any exception to be thrown from inside this method throw(int) would only allow exceptions of type int to be thrown.
Exception specifications will be dropped in C++0x. This gives a very good explanation of the reasons.
|
2,904,010 | 5,906,553 | What is the difference between C++, Java and JavaScript exception handling? | They are very different kind of languages and the way they handle exceptions might be rather different.. How is exception handling implemented and what are the implementation difference within these languages?
I am asking this question also because I noticed that C++ exception handling seems to be very slow compared to... | The most detailed answer I found regarding Exception handling and performance/implementation is on this page:
http://lazarenko.me/tips-and-tricks/c-exception-handling-and-performance
|
2,904,104 | 2,905,078 | How to differ between Windows Mobile 6.5.3 and previous versions during runtime? | Is there an established or unofficial way of finding out if my application is running on a Windows Mobile 6.5.3 device or if it's a previous version? Managed or native doesn't matter and I don't mind interop-ing.
| Since I want some reputation ;)
Here is the information I found on the web:
How to detect Windows Mobile 6.1 (Detecting AKUs)
List of AKUs on channel9
Windows CE / Windows Mobile Versions
|
2,904,137 | 2,904,827 | How best to deal with warning c4305 when type could change? | I'm using both Ogre and NxOgre, which both have a Real typedef that is either float or double depending on a compiler flag. This has resulted in most of our compiler warnings now being:
warning C4305: 'argument' : truncation from 'double' to 'Ogre::Real'
When initialising variables with 0.1 for example. Normally I wou... | The simple solution would be to just add a cast:
static_cast<Ogre::Real>(0.1);
or you could write a function to do the conversion for you (similar to your macro, but avoiding all the yucky problems macros bring:
template <typename T>
inline Ogre::Real real(T val) { return static_cast<Ogre::Real>(val); }
Then you can... |
2,904,244 | 2,904,307 | C++ Grid Controls For Desktop Applications | Is there a c++ library like Extjs that can be used in desktop applications written in c++?.
| There is also Qt which has pretty customizable Grid controls widgets and a lot of examples to learn how to use them.
|
2,904,246 | 2,904,270 | How to debug without Visual Studio? | Python -> c++ dll -> c# dll
I have a com interop c# dll that is loaded in a wrapper c++ dll throught the .tlb file generated in c# to be used in a python project. When I run in my computer it works fine but when I run in a computer that just got formated it gives:
WindowsError: exception code 0xe0434f4d
I have the red... | Download the Microsoft Debugging Tools for Windows.
It contains the WinDbg debugger, which can also be used for debugging.
Advantage of WinDbg over Visual Studio is that you have much more low-level commands to find problems.
Disadvantage of WinDbg is that it's not that user friendly (compared to Visual Studio).
|
2,904,304 | 2,904,339 | overloading -> operator in c++ | I saw this code but I couldn't understand what it does:
inline S* O::operator->() const
{
return ses; //ses is a private member of Type S*
}
so what happens now if I used ->?
| Is you have an instance of class O and you do
obj->func()
then the operator-> returns ses and then it uses the returned pointer to call func().
Full example:
struct S
{
void func() {}
};
class O
{
public:
inline S* operator->() const;
private:
S* ses;
};
inline S* O::operator->() const
{
return ses;
... |
2,904,341 | 3,418,216 | Exceptions and Access Violations in Paint events in Windows | After executing some new code, my C++ application started to behave strange (incorrect or incomplete screen updates, sometimes no screen updates at all).
After a while we found out that the new code is causing an Access Violation. Strange enough, the application simply keeps on running (but with the incorrect screen u... | It's a known defect. Check the hotfix. http://support.microsoft.com/kb/976038
|
2,904,376 | 2,904,392 | Use a template parameter in a preprocessor directive? | Is it possible to use a non-type constant template parameter in a preprocessor directive? Here's what I have in mind:
template <int DING>
struct Foo
{
enum { DOO = DING };
};
template <typename T>
struct Blah
{
void DoIt()
{
#if (T::DOO & 0x010)
// some code here
#endif
}
};
... | No, this is not possible. The preprocessor is pretty dumb, and it has no knowledge of the structure of your program. If T::Doo is not defined in the preprocessor (and it can't be, because of the ::), it cannot evaluate that expression and will fail.
However, you can rely on the compiler to do the smart thing for you:
... |
2,904,451 | 2,904,481 | refactoring my code. My headers (Header Guard Issues) | I had a post similar to this awhile ago based on a error I was getting. I was able to fix it but since then I been having trouble doing things because headers keep blocking other headers from using code. Honestly, these headers are confusing me and if anyone has any resources that will address these types of issues, th... | As I wrote in my previous answer on this question, google about Forward declaration in C++.
This may solve your problems, but, again, circular header dependencies indicate poor application design.
|
2,904,467 | 2,904,618 | Use of const double for intermediate results | I a writing a Simulation program and wondering if the use of const double is of any use when storing intermediate results. Consider this snippet:
double DoSomeCalculation(const AcModel &model) {
(...)
const double V = model.GetVelocity();
const double m = model.GetMass();
const double cos_gamma = cos(model.... | Given your code:
const double V = model.GetVelocity();
const double m = model.GetMass();
const double cos_gamma = cos(model.GetFlightPathAngleRad());
I would probably leave cos_gamma as it is. I'd consider changing V and m to references though:
const double &V = model.GetVelocity();
const double &m = model.GetMass();
... |
2,904,470 | 2,904,612 | Learning Win32 to develop GUI Applications | if you're a c++ programmer, would you go for the Win32 API or .NET to develop GUI applications?
| Win32 is an API (Application Programming Interface). So is .NET. So is POSIX. The first two have GUI toolkits integrated into the main API, but you can use other toolkits such as Qt (as suggested by Skildrick) or wxWindows instead if you choose. For *nix, the main API is POSIX and almost all of them use X11 as the ... |
2,904,622 | 2,906,029 | Resource allocation and automatic deallocation | In my application I got many instances of class CDbaOciNotifier. They all share a pointer to only one instance of class OCIEnv.
What I like to achieve is that allocation and deallocation of the resource class OCIEnv will be handled automatically inside class CDbaOciNotifier.
The desired behaviour is, with the first ins... | There is a lot going on in your code. Here is the solution, but simplified to just the bare essentials.
class CDbaOciNotifier
{
public:
CDbaOciNotifier() :
m_resource(get_env())
{ }
private:
shared_ptr<OCIEnv> m_env;
struct Delete_env
{
void operator()(OCIEnv* env)
{
OCIHand... |
2,904,694 | 2,905,083 | Parser problem - Else-If and a Function Declaration | A quick, fun question - What is the difference between a function declaration in C/C++ and an else-if statement block from a purely parsing standpoint?
void function_name(arguments) {
[statement-block]
}
else if(arguments) {
[statement-block]
}
Looking for the best solution! =)
Edit: Thanks for the insight guys.... | The two are actually completely different.
A function follows the pattern:
return-type function([argument1, argument2... argumentN]) // arguments optional
{
[statement-block]
}
An else-if on the other hand, the way you've written it in C style, is a special case of a single statement else block. Just like you can... |
2,904,839 | 2,904,843 | How can I use a class before defining it? | class Node
{
string name;
Node previous;
};
Error: Node::previous uses "Node" which is being defined.
How can I get this to work in C++? It works in C#.
EDIT:
Why Node* previous works?
| Use pointers. Node* previous; would solve the problem.
As you're doing it now, you actually try to make your class infinitely large.
|
2,904,887 | 2,905,082 | Sub-millisecond precision timing in C or C++ | What techniques / methods exist for getting sub-millisecond precision timing data in C or C++, and what precision and accuracy do they provide? I'm looking for methods that don't require additional hardware. The application involves waiting for approximately 50 microseconds +/- 1 microsecond while some external hardw... | When dealing with off-the-shelf operating systems, accurate timing is an extremely difficult and involved task. If you really need guaranteed timing, the only real option is a full real-time operating system. However if "almost always" is good enough, here are a few tricks you can use that will provide good accuracy un... |
2,905,046 | 2,905,079 | Why are some Microsoft languages called "visual"? (Visual C#, Visual Basic .NET, Visual C++) | I understand visual programming languages to be those languages that allow the programmer to to manipulate graphical--rather than textual--objects onscreen to build functionality.
The closest thing I see in C#, VB, etc. is RAD controls, but that is just composing UI and the very simplest functionality -- it has nothing... | I don't think it has to do with the languages themselves being "visual."
From the Wikipedia article:
The term Visual denotes a brand-name relationship with other Microsoft programming languages such as Visual Basic, Visual FoxPro, Visual J# and Visual C++. All of these products are packaged with a graphical IDE and su... |
2,905,329 | 2,905,352 | How to make compiler work out template class arguments at assigmnet? | Here's the code. Is it possible to make last line work?
#include<iostream>
using namespace std;
template <int X, int Y>
class Matrix
{
int matrix[X][Y];
int x,y;
public:
Matrix() : x(X), y(Y) {}
void print() { cout << "x: " << x << " y: " << y << endl; }
};
template < int a, int b, int c>
Matrix<a... | In C++11 you can use auto to do that:
auto Three=Multiply(One,Two);
In current C++ you cannot do this.
One way to avoid having to spell out the type's name is to move the code dealing with Three into a function template:
template< int a, int b >
void do_something_with_it(const Matrix<a,b>& One, const Matrix<a,b>& T... |
2,905,332 | 2,905,515 | Why does /MANIFESTUAC:NO work? | Windows 7, C++, VS2008
I have a COM DLL that needs to be registered using "runas administrator" (it is a legacy app that writes to the registry)
The DLL is used by a reports app which instantiates it using CoCreateInstance. This failed unless I also ran the reports app as administrator; until I changed the linker setti... | If your installer/registerer app has a manifest, and it says "don't run elevated", when you try to write to HKLM it fails. If you have a manifest and it says "run elevated", when you try to write to HKLM it succeeds. If you have no manifest (which you request with /MANIFESTUAC:NO), when you try to write to HKLM it wri... |
2,905,377 | 2,905,419 | "Temporary object" warning - is it me or the compiler? | The following snippet gives the warning:
[C++ Warning] foo.cpp(70): W8030 Temporary used for parameter '_Val' in call to 'std::vector<Base *,std::allocator<Base *> >::push_back(Base * const &)'
.. on the indicated line.
class Base
{
};
class Derived: public Base
{
public:
Derived() // << warning disappears if co... | Simple try:
list1.push_back(new Derived());
I am afraid there is something about POD (with trivial constructors) vs non-POD going on here.
EDIT:
Given that the code compiles fine with gcc.3.4.2 (--pedantic) I would say it's a compiler quirk. I am leaning toward MarkB explanation, ie the compiler creating a temporary e... |
2,905,578 | 2,905,716 | c++ setting string attribute value in class is throwing "Access violation reading location" | I am having some trouble getting this simple code to work:
#pragma once
#include <iostream>
#include <string>
using std::string;
class UserController;
#include "UserController.h"
class CreateUserView
{
public:
CreateUserView(void);
~CreateUserView(void);
UserController* controller;
void showView();
string name;
... | You don't seem the initialize your variable properly:
CreateUserView *_createUserView;
Therefore it is a dangling pointer, not NULL (in C++, with a few exceptions, variables are not initialized automatically to 0). So here
if(_createUserView == NULL)
{
_createUserView = new CreateUserView();
_createUserView->c... |
2,905,624 | 2,905,677 | Getting the Dimensions of an LPDIRECT3DTEXTURE9 in Direct X 9.0c? | Does anyone know if there is a function in DirectX to get the dimensions of an LPDIRECT3DTEXTURE9? I just need the width and height. If there isn't, anyone know of a quick and dirty way to accomplish this?
| LPDIRECT3DTEXTURE's may contain multiple images of different sizes. You'll have to specify which one you want. Usually, 0 is the original size, others are mipmaps that used for optimizing performance on GPU.
D3DSURFACE_DESC surfaceDesc;
int level = 0; //The level to get the width/height of (probably 0 if unsure)
myTex... |
2,905,834 | 2,907,124 | Is calling of overload operator-> resolved at compile time? | when I tried to compile the code:
(note: func and func2 is not typo)
struct S
{
void func2() {}
};
class O
{
public:
inline S* operator->() const;
private:
S* ses;
};
inline S* O::operator->() const
{
return ses;
}
int main()
{
O object;
object->func();
return 0;
}
there is a compile err... | object->func() is just syntactic sugar for object->operator->()->func() for user-defined types. Since O::operator->() yields an S*, this requires the existence of the method S::func() at compile time.
|
2,906,095 | 2,907,582 | Boost.Test: Looking for a working non-Trivial Test Suite Example / Tutorial | The Boost.Test documentation and examples don't really seem to contain any non-trivial examples and so far the two tutorials I've found here and here while helpful are both fairly basic.
I would like to have a master test suite for the entire project, while maintaining per module suites of unit tests and fixtures that ... | C++ Unit Testing With Boost.Test
(permanent link: http://web.archive.org/web/20160524135412/http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/)
The above is a brilliant article and better than the actual Boost documentation.
Edit:
I also wrote a Perl script which will
auto-generate the makefile... |
2,906,350 | 2,906,355 | Botan::SecureVector - Destructor called in Constructor? | When using the Botan::SecureVector in the following unit test:
void UnitTest()
{
std::vector<byte> vbData;
vbData.push_back(0x04);
vbData.push_back(0x04);
vbData.push_back(0x04);
Botan::SecureVector<Botan::byte> svData(&vbData[0], vbData.size());
CPPUNIT_ASSERT(vbData == std::vector<byte>(svDat... | Add line:
LibraryInitializer botanInit;
to function.
This seemed to me to be odd behavior, so I figured I should post it.
|
2,906,386 | 2,906,601 | Change IP settings using C++ | How do I change the IP settings of a Windows CE 6 box Programatically via C++? Functions for Windows might also work.
I found that I can change the hostname via sethostname but couldn't find how to change IP address settings such as:
IP Address
DHCP
Subnet
Gateway
DNS1 / DNS2
WINS1 / WINS2
Any advice / pointers would... | Have you checked out the IP Helper Routines on MSDN? I think these provide some, if not all, of what you need.
**EDIT: ** Updated link. Thanks ctacke
|
2,906,405 | 2,906,550 | Error: default parameter given for parameter 1 | Here is my class definition:
class MyClass {
public:
void test(int val = 0);
}
void MyClass::test(int val = 0) {
//
}
When I try to compile this code I get the error: "default parameter given for parameter 1"
It's just a simple function, I don't know what's wrong. I'm using Eclipse + MinGW.
| Formally, you can specify the default argument wherever you want, but you can do it only once per parameter. Even if the value is the same, it has to be specificed either in the function declaration or in the definition, but not in both.
Of course, if the declaratuion is in the header file (and the definition is in imp... |
2,906,478 | 2,907,021 | sorting char* arrays | I have a datastructure
struct record {
char cont[bufferSize];
record *next;
};
When I add new records to this structure, I want them to be sorted alphabetically. I made this function, that adds record in the right place (by alphabet) in the linked list:
record *start=NULL, *p, *x;
void recAdd(char*temp) {
... | Your code is a mess. There are a number of problems both semantic and logical, but fundamentaly the logic that decides where to insert new nodes is the most flawed. Change it to this (note my new code in the else block):
void recAdd(const char*t) {
char temp[bufferSize];
strcpy(temp, t);
p = n... |
2,906,500 | 2,906,588 | Can't cast a class with multiple inheritance | I am trying to refactor some code while leaving existing functionality in tact. I'm having trouble casting a pointer to an object into a base interface and then getting the derived class out later. The program uses a factory object to create instances of these objects in certain cases.
Here are some examples of the cla... | You have to virtually inherit from ISerializable (I just tested it with VS2010). This is a common issue called the Diamond Problem, where the compiler does not know wich hierarchy path to take.
EDIT:
This should do it:
class NewAbstract : public virtual ISerializable { ... }
class OldAbstract : public virtual ISerial... |
2,906,638 | 2,908,457 | C++0x class factory with variadic templates problem | I have a class factory where I'm using variadic templates for the c'tor parameters (code below). However, when I attempt to use it, I get compile errors; when I originally wrote it without parameters, it worked fine.
Here is the class:
template< class Base, typename KeyType, class... Args >
class GenericFactory
{
publ... | I think it's barfing here:
template <class Derived>
static void Register(const KeyType &key, FactFunType fn)
{
FnList[key] = fn;
}
You don't use Derived in this function, but it's probably messing up gcc's attempt to resolve GenericFactory<...>.Register(...). You might also want to change that to GenericFactor... |
2,906,655 | 2,906,836 | Using Windows media foundation | Ok so my new gig is high performance video (think Google streetview but movies) - the hard work is all embedded capture and image processing but:
I was looking at the new MS video offerings to display content = Windows Media Foundation.
Is anyone actually using this ?
There are no books on the topic.
The only do... | Did you read Media Foundation Programming Guide? It looks pretty complete.
|
2,907,009 | 2,907,456 | How to extract the current state of the registry? (in C/C++, XP) | I was wondering how one might extract the current state of the registry, of Windows XP, in C or C++? (While the OS is active).
I been trying to use BackupRead() on the registry-files, but it is impossible to CreateFile() them. I managed to create a Shadow Copy of the registry-files, but it wasn't the current state of t... | RegSaveKey used to be the preferred method, but the documentation now states that you should use the Volume Shadow Copy Service. I think RegSaveKey should continue to work, though (assuming you have the required privileges). Of course you could always roll your own implementation as is demonstrated in the link in one... |
2,907,087 | 2,907,116 | Embedding a scripting engine in C++ | I'm researching how to best extend a C++ application with scripting capability, and I am looking at either Python or JavaScript. User-defined scripts will need the ability to access the application's data model.
Have any of you had experiences with embedding these scripting engines? What are some potential pitfalls... | It's sure easy to embed Python by using the Boost::Python library (ok, ok, sarcasm.) Nothing is "easy" when it comes to cross-language functionality. Boost has done a great deal to aid such development. One of the developers I've worked with swears on the Boost->Python interface. His code can be programmed by a use... |
2,907,091 | 2,907,556 | How can I tell if CString allocates memory on the heap or stack? | How can I tell if the MFC CString allocates memory on the heap or stack? I am compiling for the Windows Mobile/Windows CE platform.
I am working on a project developed by someone else and I have witnessed stack overflows under certain circumstances. I am trying to figure out if the custom SQLite recordset classes (... | If you're putting an object onto the stack that contains "many" CStrings, you'll have some data on the stack and some on the heap.
The CString "management" data is what the object itself is. sizeof(CString) will tell you how big it is. It includes information about its size and the pointer to the actually character a... |
2,907,094 | 2,907,240 | C++ conversion operator between types in other libraries | For convenience, I'd like to be able to cast between two types defined in other libraries. (Specifically, QString from the Qt library and UnicodeString from the ICU library.) Right now, I have created utility functions in a project namespace:
namespace MyProject {
const icu_44::UnicodeString ToUnicodeString(const Q... | If what you're striving for is to be able to say
QStrign qs;
UnicodeString us(qs);
or
UnicodeString us;
QString qs(us);
then no, you can't do that unless you can change either of the classes. You can, of course, introduce a new string:
NewString ns;
UnicodeString us(ns);
QString qs(us);
NewString nsus(us);
NewString... |
2,907,221 | 2,907,979 | Get the lua command when a c function is called | Supposed I register many different function names in Lua to the same function in C. Now, everytime my C function is called, is there a way to determine which function name was invoked?
for example:
int runCommand(lua_State *lua)
{
const char *name = // getFunctionName(lua) ? how would I do this part
for(int i = 0; ... | Another way to attack your question is by using upvalues. Basically, you register the C functions with the function below instead of lua_register:
void my_lua_register(lua_State *L, const char *name, lua_CFunction f)
{
lua_pushstring(L, name);
lua_pushcclosure(L, f, 1);
lua_setglobal(L, name);
}
Then... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.