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,549,235 | 2,549,346 | Qt Stylesheets with derived classes | Can I use Qt stylesheets with a derived widget? I'd like to be able to define some custom properties on the widget (like various colors) and be able to define their value in a stylesheet.
Is this possible?
| Sure, just declare your properties with Q_PROPERTY.
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY( int fun READ getFun WRITE setFun )
public:
MyClass( QObject * parent=0, const char * name=0 );
~MyClass();
void setFun( int x );
int getFun() const;
};
|
2,549,600 | 2,549,653 | C++ Memory Allocation & Linked List Implementation | I'm writing software to simulate the "first-fit" memory allocation schema.
Basically, I allocate a large X megabyte chunk of memory and subdivide it into blocks when chunks are requested according to the schema.
I'm using a linked list called "node" as a header for each block of memory (so that we can find the next blo... | memset(void* memory, int value, size_t size)
So, it's not to copy the head_node into head_ptr (you are thinking of memcpy),
it's for initializing memory (clearing to 0, marking as freed, etc...).
In this case, you could simply cast the head_ptr to a node*:
node* head_node = (node*)head_ptr;
And now you don't have to ... |
2,549,618 | 2,550,069 | Is there any g++ option to dump class layout and vtables? | I want to see how g++ lays out memory for classes and virtual tables.
Is there a way to dump this information, using g++'s options?
| g++ -fdump-class-hierarchy -c source_file.cpp
|
2,549,722 | 2,549,734 | Boost C++ Singleton error LNK2001: unresolved external symbol "private: static long Nsp::HL::flag" (?flag@HL@Nsp@@0JA) | I try to create a multi-threaded singleton pattern class.
Header:
class HL{
public:
static HL* getInstance();
.........
private:
static HL* instance;
static boost::once_flag flag;
HL();
static void initOnce();
}
CPP:
HL* HL::instance = NULL;
HL* HL::getInstance(){
... | You need to define the static member variable in the cpp file:
boost::once_flag Nsp::HL::flag;
You can initialize it if you need to (I've not used boost::once_flag, and can't tell you whether or how it needs to be initialized):
boost::once_flag Nsp::HL::flag = {whatever goes here};
|
2,549,727 | 2,549,751 | C++ instantiating a class within a method, then altering member variables from a different method? | Say I have a method, and within that method it instantiates a Person class:
void methodA()
{
Person personObject;
}
How would I access that object's methods from within another method? I.e. something like:
void methodB()
{
personObject.someMethod();
}
I realise it's a painfully nooby question :P
| Pass a reference to the other function.
void methodB(Person &personObject)
{
personObject.someMethod();
}
void methodA()
{
Person personObject;
methodB(personObject);
}
|
2,549,743 | 3,087,308 | how to get AutoIncrement value after JetUpdate() in Extensible Storage Engine (JetBlue) | after calling JetSetColumns() and then JetUpdate() how do I retrieve the values for any freshly assigned autoincrement values?
| when you call JetUpdate() the third arg is a 'bookmark'. Once JetUpdate() completes you can seek to the bookmark using
JetGotoBookmark() - http://msdn.microsoft.com/en-us/library/ms683554(EXCHG.10).aspx
|
2,549,801 | 2,549,936 | How do interpreters functions written in the class C++ in the main | I'm working on a project about Data structures.
In the first , I wrote everything in main but it sounds like C . But as I learned, I tried to thinkk OOP and do as little as possible in my main() methods.
I've implemented some opertation in my class like add,delet,find.it's too easy to implement its .
class ARB
{
... | There's a few issues here. For one thing, add() is a member function of ARB, not BT. And, BT is a private subclass of ARB, so it can't be accessed from main(). p is a private member of ARB (as it should be), but it should really be a direct variable, not a pointer, so it will be automatically created and destroyed with... |
2,549,856 | 2,549,876 | c++ global operator not playing well with template class | ok, i found some similar posts on stackoverflow, but I couldn't find any that pertained to my exact situation and I was confused with some of the answers given. Ok, so here is my problem:
I have a template matrix class as follows:
template <typename T, size_t ROWS, size_t COLS>
class Matrix
{
public:
te... | Your operator+= here:
Matrix<T, ROWS, COLS> & operator+=( const T & value )
Defines a method of adding a T (a scalar) to a Matrix<T, ROWS, COLS>.
This statement:
return returnValue += lhs;
Attempts to add a Matrix<T, ROWS, COLS> (a matrix, the type of lhs) to a Matrix<T, ROWS, COLS>.
So the compiler is completely cor... |
2,549,957 | 2,549,991 | comparing two end() iterators | list<int> foo;
list<int> foo2;
list<int>::iterator foo_end = foo.end();
list<int>::iterator foo2_end = foo2.end();
for (list<int>::iterator it = foo.begin(); it != foo2_end; ++foo) <- notice != comparison here
{
...
it this allowed? will it work correctly.
I am inclined to think that this is implementation depende... | There was a defect reported about this (LWG defect 446). The defect report asked whether it is valid to compare iterators that refer to elements of different containers.
Notes in the defect report explain that it was certainly the intention that doing so is undefined, but it is not explicitly stated that it is undefin... |
2,550,051 | 2,569,064 | How to acquire still webcam image | I need some help deciding what to use to acquire an image from a webcam. I want to acquire a single image. I know you can typically acquire a still image at a higher resolution than a single video frame.
Currently, I am using MATLAB's image acquisition toolbox.. which apparently only supports obtaining frames in video... | Are you referring to the fact that the largest resolution reported by the Image Acquisition Toolbox is (for example) 1024x768 but the webcam claims that it can acquire 6 megapixel still images? If so, every webcam that I have ever seen has a note in very small print somewhere that explains that the higher resolution i... |
2,550,085 | 2,550,141 | Where is pure virtual function located in C++? | Which virtual table will be pure virtual function located? In the base class or derived class?
For example, what does the virtual table look like in each class?
class Base {
virtual void f() =0;
virtual void g();
}
class Derived: public Base{
virtual void f();
virtual void g();
}
| g++ -fdump-class-hierarchy layout.cpp produces a file layout.cpp.class. The content of layout.cpp.class will show the following:
Vtable for Base
Base::_ZTV4Base: 4u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI4Base)
16 __cxa_pure_virtual
24 Base::g
Class Base
size=8 align=8
base size=8 base a... |
2,550,229 | 2,567,805 | How to keep only duplicates efficiently? | Given an STL vector, output only the duplicates in sorted order, e.g.,
INPUT : { 4, 4, 1, 2, 3, 2, 3 }
OUTPUT: { 2, 3, 4 }
The algorithm is trivial, but the goal is to make it as efficient as std::unique(). My naive implementation modifies the container in-place:
My naive implementation:
void not_unique(vector<int>* ... | Shorter and more STL-ish than previous entries. Assumes sorted input.
#include <algorithm>
#include <functional>
template< class I, class P >
I remove_unique( I first, I last, P pred = P() ) {
I dest = first;
while (
( first = std::adjacent_find( first, last, pred ) )
!= last ) {
* ... |
2,550,281 | 2,550,430 | Floating point vs integer calculations on modern hardware | I am doing some performance critical work in C++, and we are currently using integer calculations for problems that are inherently floating point because "its faster". This causes a whole lot of annoying problems and adds a lot of annoying code.
Now, I remember reading about how floating point calculations were so slow... | Alas, I can only give you an "it depends" answer...
From my experience, there are many, many variables to performance...especially between integer & floating point math. It varies strongly from processor to processor (even within the same family such as x86) because different processors have different "pipeline" lengt... |
2,550,377 | 2,550,405 | When pass-by-pointer is preferred to pass-by-reference in C++? | I can imagine one case, in which the input parameter could be NULL so that pass-by-pointer is preferred but not pass-by-reference?
Can anybody add more cases?
| Some like pass-by-pointer better in cases where the object being passed is actually going to be modified. They use pass-by-const-reference when the object is being passed by reference in order to avoid a copy of the object, but will not be changed in the function.
In illustration, take the following functions:
int foo... |
2,550,628 | 2,654,178 | How to use external makefile in Eclipse | I have a source code of an OpenSource project which I get from SVN. I was able to run autogen --> configure --> and make successfully (through the terminal). But I want to build the same project with Eclipse, and I can't port manually those source files to eclipse though. So, How can I set Eclipse to use external make ... | Ok, I got it, It was straightforward. Just go to project properties --> C/C++ Build --> Make file generation --> and untick "Generate Make files automatically". In additionally you may have to set the Build location also.
|
2,550,730 | 2,550,742 | i want to know VC++ 6.0 uses .Net frame work or not? | i am doubtful about it that vc++6.0 is .Net framework independent or depends on it help required?
| VC++ 6.0 does not depend on .NET. It shipped as part of the last set of Microsoft development tools before the debut of .NET. You can rest assured, though, that even versions of VC++ since then don't bring in .NET by default--they only use .NET if you compile with managed extensions turned on.
|
2,550,748 | 2,551,438 | How to capture full screen in c using visual studio | Is it possible to capture full screen in visual studio (VC++), so that user don't have to press ATL+Enter. Kindly guide me how I can make it possible.
| If you need to enter fullscreen mode in OpenGL per default, check out NeHe Productions, for instance his second lesson
If you download his example at the bottom of the screen and check out the:
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
.. you will see how it can be made in O... |
2,550,822 | 2,550,873 | "call" instruction that seemingly jumps into itself | I have some C++ code
#include <cstdio>
#include <boost/bind.hpp>
#include <boost/function.hpp>
class A {
public:
void do_it() { std::printf("aaa"); }
};
void
call_it(const boost::function<void()> &f)
{
f();
}
void
func()
{
A *a = new A;
call_it(boost::bind(&A::do_it, a));
}
which gcc 4 compiles into... | The call is probably to an external function, and the address you see (FFFFFFFC) is just a placeholder for the real address, which the linker and/or loader will take care of later.
|
2,551,491 | 2,551,516 | function pointer error | Can anybody help me with this simple code??
#include <iostream>
using namespace std;
void testFunction(){
cout<<"This is the test function 0"<<endl;
}
void testFunction1(){
cout<<"This is the test function 1"<<endl;
}
void testFunction2(){
cout<<"This is the test function 2"<<endl;
}
void (*fp[])()={tes... | You're trying to use a function pointer as an array index. That won't fly, array indices must be integer.
To call through a function pointer, just call:
(*fp[1])();
or the (even shorter!)
fp[1]();
will work.
|
2,551,539 | 2,552,312 | Generate accessors in Visual C++ 2008 | I'm trying to generate the accessors and mutators for my variables automatically, but just can't find a way. I tried the right-click/refactor... solution, but the refactor item doesn't appear.
I'm not in the mood right now to learn how to write a macro to do this, and I don't have the money to buy a commercial solution... | No, C++ doesn't have syntax for accessors. C++ programmers frown on features that are not well supported by the language. Nor does if have many Resharper style tools. If you don't like to type then C++ is not a language you should consider.
Keep Neil happy and avoid the "bad design" put-down by omitting the "get" pr... |
2,551,634 | 3,516,270 | Visual studio macro - getting started | copy a definition from .cpp to .h | Is it possible to do a macro that copies a definition of a function to a declaration(, and maybe also the opposite)? For instance
Foo::Foo(int aParameter, int bParameter){
//
}
int Foo::someMethod(char aCharacter) const {
return 0;
}
From the .cpp file would be:
class Foo {
Foo(int aParameter, int bPa... | So, I found the Automation and Extensibility for Visual Studio, which covers the stuff I am trying to do, with a little help from the object browser and record macro function.
I guess I should be able to solve it from here.
|
2,551,657 | 2,552,540 | C++: how can I test if a number is power of ten? | I want to test if a number double x is an integer power of 10. I could perhaps use cmath's log10 and then test if x == (int) x?
edit: Actually, my solution does not work because doubles can be very big, much bigger than int, and also very small, like fractions.
| A lookup table will be by far the fastest and most precise way to do this; only about 600 powers of 10 are representable as doubles. You can use a hash table, or if the table is ordered from smallest to largest, you can rapidly search it with binary chop.
This has the advantage that you will get a "hit" if and only if... |
2,551,667 | 2,551,701 | Trying to write a std::iterator : Compilation error | I am trying to write an std::iterator for the CArray<Type,ArgType> MFC class. This is what I have done till now:
template <class Type, class ArgType>
class CArrayIterator : public std::iterator<std::random_access_iterator_tag, ArgType>
{
public:
CArrayIterator(CArray<Type,ArgType>& array_in, int index_in = 0)
... | You've said that your iterator is a "random access iterator". Part of the requirements for random access iterators is that you provide <, <=, > and >= comparision operators, with < giving a strict weak ordering and the usual relationships between them.
You need to provide the appropriate comparison operators, or you co... |
2,551,877 | 2,554,122 | Wrong EOF when unzipping binary file | I tried to unzip a binary file to a membuf from a zip archive using Lucian Wischik's Zip Utils:
http://www.wischik.com/lu/programmer/zip_utils.html
http://www.codeproject.com/KB/files/zip_utils.aspx
FindZipItem(hz, filename.c_str(), true, &j, &ze);
char *content = new char[ze.unc_size];
UnzipItem(hz, j, content, ze.unc... | It may be unzipping just fine. Keep in mind that many string oriented display functions will stop outputting characters at the first '\0'. Even your debugger will display a char* as if it were a string in your watch window. It can only guess what the data is in a character array... How are you testing how many bytes we... |
2,551,891 | 2,713,187 | boost.serialization and lazy initialization | i need to serialize directory tree.
i have no trouble with this type:
std::map<
std::string, // string(path name)
std::vector<std::string> // string array(file names in the path)
> tree;
but for the serialization the directory tree with the content i need other type:
std::map<
std::string, // string(path name... | I would replace the std::string in the vector by a custom class, let me say MyFileNames
class MyFileNames : std::string
{
// add forward constructors as needed
};
std::map<
std::string, // string(path name)
std::vector<MyFileNames> // string array(file names in the path)
> tree;
And define the save serializati... |
2,552,034 | 2,561,899 | Generate header of view .obj file | Is there a way to generate a c++ header file for an .obj file? Or perhaps is there an utility that can view .obj files. I've already found objconv that converts between formats, but I can't find any .h generator/viewer.
| Given the C++ tag, the situation isn't quite as hopeless as some of the other answers imply.
In particular, at least with most C++ compilers, the name of a function will be mangled (Microsoft calls it "decorated") to indicate the parameters taken by that function. The mangling scheme varies from one compiler to another... |
2,552,046 | 2,552,107 | How to pass operators as parameters | I have to load an array of doubles from a file, multiply each element by a value in a table (different values for different elements), do some work on it, invert the multiplication (that is, divide) and then save the data back to file.
Currently I implement the multiplication and division process in two separate method... | Make TransformData a template function:
template <typename F>
typename F::result_type TransformData(double data, F f) { ... }
Call it thus:
double MultiplyData(double data) {
return TransformData(data, std::multiplies<double>());
}
std::binary_function is a tagging class. It's primary purpose is not to provide a ... |
2,552,165 | 2,552,342 | Finding missing symbols in libstdc++ on Debian/squeeze | I'm trying to use a pre-compiled library provided as a .so file.
This file is dynamically linked against a few librairies :
$ ldd /usr/local/test/lib/libtest.so
linux-gate.so.1 => (0xb770d000)
libstdc++-libc6.1-1.so.2 => not found
libm.so.6 => /lib/i686/cmov/libm.so.6 (0xb75e1000)
libc.so.6 => /lib/i686/cmov/libc.so.... | Google says that you need libstdc++2.9-glibc2.1
http://linux.derkeiler.com/Mailing-Lists/Debian/2005-07/0755.html
Although it's from obsolete debian release and I'm not sure if it's such a good idea to install it.
Edit
Actually I tried it out of curiosity. It didn't do any harm and seem to coexist well with standard li... |
2,552,172 | 2,552,959 | Thread Synchronisation 101 | Previously I've written some very simple multithreaded code, and I've always been aware that at any time there could be a context switch right in the middle of what I'm doing, so I've always guarded access the shared variables through a CCriticalSection class that enters the critical section on construction and leaves ... | Q1: Using the "volatile" keyword
In VS2005 and later the C++ compiler surrounds access to this variable using memory barriers, ensuring that the variable is always completely written/read to the main system memory before using it.
Exactly. If you are not creating portable code, Visual Studio implements it exactly thi... |
2,552,416 | 2,552,458 | How can I find the user's home dir in a cross platform manner, using C++? | How can I find the user's home directory in a cross platform manner in C++? i.e. /home/user in Linux, C:\Users\user\ on Windows Vista, C:\Documents And Settings\user\ on Windows XP, and whatever it is that Macs use. (I think it's /User/user)
Basically, what I'm looking for is a C++ way of doing this (example in python)... | I don't think it's possible to completely hide the Windows/Unix divide with this one (unless, maybe, Boost has something).
The most portable way would have to be getenv("HOME") on Unix and concatenating the results of getenv("HOMEDRIVE") and getenv("HOMEPATH") on Windows.
|
2,552,940 | 2,553,014 | Executing certain code for every method call in C++ | I have a C++ class I want to inspect. So, I would like to all methods print their parameters and the return, just before getting out.
The latter looks somewhat easy. If I do return() for everything, a macro
#define return(a) cout << (a) << endl; return (a)
would do it (might be wrong) if I padronize all returns to par... |
However, printing inputs seems more
difficult. Is there a way I can do it,
using C++ structures or with a
workaroud hack?
No.
Update: I'm going to lose some terseness in my answer by suggesting that you can probably achieve what you need by applying Design by Contract.
|
2,553,015 | 2,553,215 | Tangent of a parametric discrete curve | I have a parametric curve, say two vectors of doubles where the parameter is the index, and I have to calculate the angle of the tangent to this curve at any given point (index).
Any suggestion or link about how to do that?
Thanks.
| The tangent to a smooth curve at a point P is the parametric straight line P + tV, where V is the derivative of the curve with respect to "the parameter". But here the parameter is just the index of an array, and numerical differentiation is a difficult problem, hence to approximate the tangent I would use (weighted) l... |
2,553,149 | 2,553,208 | Area of a irregular shape | I have set of points which lies on the image. These set of points form a irregular closed shape. I need to find the area of this shape. Does any body which is the normal algorithm used for calculating the area ? Or is there any support available in libraries such as boost? I am using C++.
| If you polygon is simple (it doesn't have any point in common except for the pairs of consecutive segments) then wikipedia comes to help you:
The formula for the area is
(it assumes that the last point is the same of the first one)
You can easily implement it as
float area = 0.0f;
for (int i = 0; i < numVertices - 1;... |
2,553,397 | 2,553,452 | Why does the MSCVRT library generate conflicts at link time? | I am building a project in Visual C++ 2008, which is an example MFC-based app for a static C++ class library I will be using in my own project soon. While building the Debug configuration, I get the following:
warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
After using... | This usually happens when you link against a static library that uses another version of the VC++ runtime (C++ ->Code Generation->Runtime Library setting in the project properties).
|
2,553,488 | 2,553,736 | How to log when a particular memory location gets written and by which function? | I have a bug which happens very rarely but crashes my C++ program. It's seems I have a buffer overflow problem or something similar. I find that these types of bug are the most difficult to diagnose.
My program always crashes because of the same corrupted memory location. Is there some debugging tool which could detect... | If you are using Visual C++ then look up data breakpoints.
|
2,553,522 | 2,553,533 | Interview question: Check if one string is a rotation of other string | A friend of mine was asked the following question today at interview for the position of software developer:
Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ?
Example:
If s1 = "stackoverflow" then the following are some of its rotated versions:
"tackoverflows"
"ackoverflowst"
"overflowst... | First make sure s1 and s2 are of the same length. Then check to see if s2 is a substring of s1 concatenated with s1:
algorithm checkRotation(string s1, string s2)
if( len(s1) != len(s2))
return false
if( substring(s2,concat(s1,s1))
return true
return false
end
In Java:
boolean isRotation(String s1,Strin... |
2,553,706 | 2,553,838 | What's the difference between starting a process from the dock vs. the command line on OS X | I'm debugging an issue on OS X that only occurs when the application is started from the dock. It does not happen when the app is started from the command line. What is the difference between the two scenarios? The code I'm working with is a c++ based bundled plug-in being loaded in a third party app. I've attached... | One important difference is that the initial working directory will be different in each case. Applications should never make any assumptions about the working directory and will break in interesting ways if they do.
|
2,554,082 | 2,554,098 | Array performance question | I am very familiar with STL vector (and other container) performance guarantees, however I can't seem to find anything concrete about plain arrays.
Are pointer arithmetic and [] methods constant or linear time?
| They are constant time. (Same as vector.)
When you say a[b], it becomes *(a + b). Both (pointer arithmetic) addition and dereferencing are constant time.
When adding an integer to a pointer, it moves that many elements over:
T* p; size_t i;
T* q = p + i; // same as:
T* q = reinterpret_cast<T*>(reinterpret_cast<char*>(... |
2,554,215 | 2,554,417 | C++: Conceptual problem in designing an intepreter | I'm programming an interpreter for an experimental programming language (educational, fun,...)
So far, everything went well (Tokenizer & Parser), but I'm getting a huge problem with some of the data structures in the part that actually runs the tokenized and parsed code.
My programming language basically has only two t... | The problem comes from the fact, that your symbol class is a type that contains two different types that you are trying to identify through the single type of the class Symbol.
It would be better to polymorphically create the symbols:
class Symbol
{
public:
virtual Symbol& operator = (int val) = 0; // Pure virtual
... |
2,554,221 | 2,554,247 | How to check if memory has been initialized? | Is there a way of checking if memory pointed to by pointer has been initialized?(not necessarily by my program).
Thanks
| No.
Uninitialized memory can contain anything, including bytes that make it look like it has been initialized.
|
2,554,405 | 2,554,450 | Sort a list of pointers | Once again I find myself failing at some really simple task in C++. Sometimes I wish I could de-learn all I know from OO in java, since my problems usually start by thinking like Java.
Anyways, I have a std::list<BaseObject*> that I want to sort. Let's say that BaseObject is:
class BaseObject {
protected:
int id;
p... | You are looking at doing double dispatch - that is calling a virtual function depending on the types of two objects rather than one. Take a look at this wikipedia article for a heads-up http://en.wikipedia.org/wiki/Double_dispatch. I have to say that whenever I find myself in this situation, I try to change direction :... |
2,554,447 | 2,554,524 | How to use WaitForSingleObject | In order to try out how to program with the Win32 API, I wrote a program that creates a process.
Then I want to check if my process waits for the newly created process, close the handle and then check WaitForSingleObject again (the second process is sleeping for 700 ms)
First process:
#include <iostream>
#include <wind... | You really need to pay attention to the meaning for the return value of the API functions. You cannot ignore a FALSE return from CreateProcess(). WaitForSingleObject() can return several values, it returns 0 if the wait completed successfully. Which makes you print "false".
|
2,554,462 | 2,554,547 | c++ template and its element type | This is my template matrix class:
template<typename T>
class Matrix
{
public:
....
Matrix<T> operator / (const T &num);
}
However, in my Pixel class, I didn't define the Pixel/Pixel operator at all!
Why in this case, the compiler still compiles?
Pixel class
#ifndef MYRGB_H
#define MYRGB_H
#include <iostream>
using n... | C++ templates are instantiated at the point you use them, and this happens for the Matrix<T>::operator/(const T&), too. This means the compiler will allow Matrix<Pixel>, unless you ever invoke the division operator.
|
2,554,490 | 2,554,530 | Learning C++ as a Perl programmer | I'm a Perl5 programmer for 7 years and I'm trying to learn C++ now.
Some of the C++ syntax is hard for me to understand and to think in C++ way.
For example:
In Perl, you can mix the data in the arrays
@array = (1,"string",5.355);
You can assign any value to a scalar variable:
$var = 1;
$var = "string";
$var = \$refer... | "C++ For Perl Programmers" is a pretty specific request. Given that Perl abstracts away more of the machine than C++ does, I think that a good way to start would be to forget what you know about Perl and get a regular C++ book.
For example, it seems reasonable to you that you should be allowed to have multiple data ty... |
2,554,867 | 2,561,332 | Changing the system time zone succeeds once and then no longer changes | I'm using the WinAPI to set the time zone on a Windows XP SP3 box. I'm reading the time zone information from the HKLM\Software\Microsoft\WindowsNT\Time Zones\<time zone name> key and then setting the time zone to the specified time zone.
I enumerate the keys under the Time Zones key, grab the TZI value and stuff it i... | After messing with this for awhile I've fixed the issue but I'm not quite sure what step fixed it. I added an extra clause to check the OS to verify whether or not to adjust the process token to enable the SE_TIME_ZONE_NAME. It now only does this on post-XP OS's.
I also changed how the TZI registry value was stored in... |
2,554,934 | 2,554,940 | Array pointer arithmetic question | Is there a way to figure out where in an array a pointer is?
Lets say we have done this:
int nNums[10] = {'11','51','23', ... }; // Some random sequence
int* pInt = &nNums[4]; // Some index in the sequence.
...
pInt++; // Assuming we have lost track of the index by this stage.
...
Is ther... | Yes:
ptrdiff_t index = pInt - nNums;
When pointers to elements of an array are subtracted, it is the same as subtracting the subscripts.
The type ptrdiff_t is defined in <stddef.h> (in C++ it should be std::ptrdiff_t and <cstddef> should be used).
|
2,554,957 | 2,560,675 | Inclusion of dshow.h results in definition errors | I am trying to do a few things using DirectShow for audio playback. I have a header file, at the top is:
#pragma once
#include <dshow.h>
#pragma comment(lib, "strmiids.lib")
and then it goes on to define a class.
When including dshow.h I get the following complilation errors:
C:\Program Files\Microsoft SDKs\Windows\v... | Fixed this by changing the order of the #include definitions. I moved the header file that the above code was defined in to the top and it works ok now. Must have been a clash with some code in another file, possibly some directSound related stuff.
|
2,555,022 | 2,564,363 | Can shared memory be read and validated without mutexes? | On Linux I'm using shmget and shmat to setup a shared memory segment that one process will write to and one or more processes will read from. The data that is being shared is a few megabytes in size and when updated is completely rewritten; it's never partially updated.
I have my shared memory segment laid out as foll... | Joe Duffy gives the exact same algorithm and calls it: "A scalable reader/writer scheme with optimistic retry".
It works.
You need two sequence number fields.
You need to read and write them in opposite order.
You might need to have memory barriers in place, depending on the memory ordering guarantees of the system.
... |
2,555,033 | 2,555,048 | Linker error: wants C++ virtual base class destructor | I have a link error where the linker complains that my concrete class's destructor is calling its abstract superclass destructor, the code of which is missing.
This is using GCC 4.2 on Mac OS X from XCode.
I saw g++ undefined reference to typeinfo but it's not quite the same thing.
Here is the linker error message:
Und... | Even if you declare a destructor as a pure virtual function, you must provide an implementation for it. Although you cannot instantiate an abstract class directly, it is always instantiated when you instantiate one of its derived (concrete) classes. And so at some point such instances will be destroyed, thus requiring ... |
2,555,173 | 2,555,270 | C++ include header conventions | Suppose I have a file X.h which defines a class X, whose methods are implemented in X.cc.
The file X.h includes a file Y.h because it needs Y to define class X. In X.cc, we can refer
to Y because X.h has already included Y.h. Should I still include Y.h in X.cc ?
I understand that I don't need to and I can depend on h... | Be minimal. In headers, prefer forward declarations to full definitions. Use iosfwd instead of ostream, for example.
That said, X.h and X.cc represent the same logical unit. If your dependency on Y.h ever changed (for example, turned it into a forward declaration), you'd be changing the class anyway. So you can move #i... |
2,555,389 | 2,555,513 | GLSL Error: failed to preprocess the source. How can I troubleshoot this? | I'm trying to learn to play with OpenGL GLSL shaders. I've written a very simple program to simply create a shader and compile it. However, whenever I get to the compile step, I get the error:
Error: Preprocessor error
Error: failed to preprocess the source.
Here's my very simple code:
#include <GL/gl.h>
#include <GL... | If you're just starting out you may be better off by running against the Mesa software renderer, which should provide full (though slow) OpenGL 2.1 support.
|
2,555,522 | 2,555,555 | Can operator= may be not a member? | Having construction in a form:
struct Node
{
Node():left_(nullptr), right_(nullptr)
{ }
int id_;
Node* left_;
Node* right_;
};
I would like to enable syntax:
Node parent;
Node child;
parent.right_ = child;
So in order to do so I need:
Node& operator=(Node* left, Node right);
but I'm getting msg that operator= has to... | An automatic conversion from value to pointer creates lots of possibilites to make your code hard to understand.
If you still want to do it you can provide a conversion operator on your Node class:
operator Node* () { return this; }
|
2,555,712 | 2,585,471 | C++ visitor pattern handling templated string types? | I'm trying to use the visitor pattern to serialize the contents of objects. However one snag I'm hitting is when I'm visiting strings. My strings are of a templated type, similar to STL's basic_string. So something like:
basic_string<char_type, memory_allocator, other_possible_stuff> \\ many variations possible!
Since... | In the end, I went with a slightly different approach. Instead of hoping to use a visitor with templated methods (which is, of course, impossible), I decided to pass a visitor-like class as a template parameter to my object's visit method. Totally simplified example:
class SomeKindOfVisitor // doesn't need to derive f... |
2,555,849 | 2,555,963 | C++ universal data type | I have a universal data type, which is passed by value, but does not maintain the type information. We store only pointers and basic data types(like int, float etc) inside this. Now for the first time, we need to store std::string inside this. So we decided to convert it into std::string* and store it. Then comes the p... | One major flaw with this approach is that you really need a reference count, not a single bit "has been copied" flag. The bit won't work if you copy the string multiple times. As written, you will get into trouble if you create a copy of an Atom and delete the copy before the original:
Atom a("hello world");
if (...) ... |
2,556,475 | 2,556,514 | Looking for a good C++/.net book | I have recently started to feel that I need to greatly improve my C++ skills especially in the realm of .net. I graduated from a good four year university with a degree in computer science about 9 months ago and I have since been doing full time contract work for a small software company in my local area. Most of my ... | Depends what you actually want to learn:
If you want to learn about .Net, I would learn C# rather than C++.
If you want to learn C++, do not learn C++/CLI - learn the language described by the C++ Standard. For C++ books, see The Definitive C++ Book Guide and List. I personally would recommend Accelerated C++.
|
2,556,532 | 2,556,563 | How often will a programmer be asked to write a makefile file? | Is makefile an advanced problem or a general problem for a programmer?
For a C++ programmer, how often will he be asked to write a makefile file?
| Nobody ever writes a Makefile. They take an existing Makefile and modify it.
Just be thankful you don't have to deal with IMakefile. (For those of you who were lucky enough to never deal with this, or who have managed to forget, IMakefile was a file that was sort of a meta-Makefile for X Window System based projects ... |
2,556,945 | 2,556,995 | "this" pointer changes in GDB backtrace | I am examining a core dump, and noticed that in one frame the 'this' pointer is different than in the next frame (in the same thread). Not just a little different, it went from 0x8167428 to 0x200.
I am not that well-versed in using GDB, but this does not seem right to me. Is this problematic, and if so, what could be t... | The this pointer can change between frames in a gdb trace if the function in the next frame is called on a different object (even if the objects are the same type), since this is for the specific instance. This is probably not your problem.
0x200 is not a valid value for this, and almost certainly indicates memory cor... |
2,556,984 | 2,559,674 | OpenSteer on Xbox 360? | I want to use OpenSteer for my game that I want to be compatible with the Xbox 360. I have heard that since it is a wrapper for a C++ library, it will work in XNA on a PC, but not on the Xbox. Is there no way to make it compatible?
UPDATE: The C++ version may not be, but what about OpenSteerDotNet?
| According to the OpenSteerDotNet homepage:
It should work fine with XNA Game
Studio Express, including the XBox 360
runtime.
|
2,557,007 | 2,557,158 | How do i generate all possible subsets of an binary string? | i have a problem, that i don't know how to solve it.
i have a binary string and i want to generate all possible binary substrings.
Example :
input : 10111
output: 10000, 10100,00111,00001,10110 ...
How can i do this , fast AND Smart ?
| Magic - assumes bitmask though:
subset( int x )
list = ()
for ( int i = x; i >= 0; i = ( ( i - 1 ) & x ) )
list.append( i )
return list
You can use the same logic, though it's a little bit more involved, with a binary string.
|
2,557,248 | 2,559,465 | Encapsulating user input of data for a class | For an assignment I've made a simple C++ program that uses a superclass (Student) and two subclasses (CourseStudent and ResearchStudent) to store a list of students and print out their details, with different details shown for the two different types of students (using overriding of the display() method from Student).
... | As mentioned by scv, it is normally better to decouple presentation (view) from internal structure (model).
Here you have a typical case:
the Student class, root of a model hierarchy
the Displayer class, root of another independent hierarchy
The issue with the display is that it varies according to two elements, whic... |
2,557,375 | 2,557,777 | What is the correct Qt idiom for exposing signals/slots of contained widgets? | Suppose I have a MyWidget which contains a MySubWidget, e.g. a custom widget that contains a text field or something. I want other classes to be able to connect to signals and slots exposed by the contained MySubWidget instance. Is the conventional way to do this:
Expose a pointer to the MySubWidget instance through a... | If you look at Qt's own code they prefer option 2.
For example, look at QTabWidget and QTabBar. They share a number of signals and slots, yet QTabWidget hides the fact that it uses a QTabBar (well, sorta... QTabWidget::tabBar() obviously breaks this even though it's protected).
Although this will result in more code, I... |
2,557,438 | 2,557,463 | Need to skip newline char (\n) from input file | I am reading in a file into an array. It is reading each char, the problem arises in that it also reads a newline in the text file.
This is a sudoku board, here is my code for reading in the char:
bool loadBoard(Square board[BOARD_SIZE][BOARD_SIZE])
{
ifstream ins;
if(openFile(ins)){
char c;
while(!ins.e... | Well in your file format you can simply not save newlines, or you can add a ins.get() the for loop.
You could also wrap your c=ins.get() in a function something like getNextChar() which will skip over any newlines.
I think you want something like this:
for (int index1 = 0; index1 < BOARD_SIZE; index1++)
{
for (int ... |
2,557,551 | 2,562,302 | How get list of local network computers? | I am trying to get a list of local network computers. I tried to use NetServerEnum and WNetOpenEnum API, but both API return error code 6118 (ERROR_NO_BROWSER_SERVERS_FOUND). Active Directory in the local network is not used.
Most odd Windows Explorer shows all local computers without any problems.
Are there other ways... | I found solution using interface IShellItem with CSIDL_NETWORK. I get all network PC.
C++: use method IShellFolder::EnumObjects
C#: you can use Gong Solutions Shell Library
using System.Collections;
using System.Collections.Generic;
using GongSolutions.Shell;
using GongSolutions.Shell.Interop;
public sealed class ... |
2,557,562 | 8,095,478 | Using Apple autorelease pools without Objective-C | I am developing an application that needs to work on Linux, Windows and Mac OS X. To that purpose, I am using C++ with Qt.
For many reasons, on Mac OS X, I need to use CoreFoundation functions (such as CFBundleCopyBundleURL) that creates core objects that need to be released with CFRelease. But doing so generate a lots... | id is a C declaration. You can simply add scope based autorelease pools to your cpp program like so:
autorelease_pool.hpp
class t_autorelease_pool {
public:
t_autorelease_pool();
~t_autorelease_pool();
private:
id d_pool; // << you may opt to preprocess this out on other platforms.
private:
t_autoreleas... |
2,557,565 | 2,558,120 | HttpAddUrl permissions | I'm trying to run a custom WinHTTP based web-server on Windows Server 2008 machine.
I pass "http://*:22222/" to HttpAddUrl
When I start my executable as Administrator or LocalSystem everything works fine. However if I try to run it as NetworkService to minimize security risks (since there are no legitimate reasons for ... | You must be an administrator to add URLs to the http.sys URL mappings. Network Service does is not a member of the admin group, but the admnistrator's group and the System account are members.
IIS gets around this by having one process, inetinfo.exe, that runs as SYSTEM and sets up the URL mappings for worker processes... |
2,557,598 | 2,557,662 | How can I make a fixed hex editor? | So. Let's say I were to make a hex editor to edit... oh... let's say a .DLL file. How can I edit a .DLL file's hex by using C# or C++? And for the "fixed part", I want to make it so that I can browse from the program for a specific .DLL, have some pre-coded buttons on the programmed file, and when the button is pressed... | The basics are very simple.
A DLL, or any file, is a stream of bytes.
Basic file operations allow you to read and write arbitrary portions of a file. The term of art is basically "Random Access Files Operations".
In C, the fundamental operations are read(), write(), and lseek().
read allows you to read a stream of byte... |
2,557,638 | 2,557,641 | How to read character from console in c++? | I'm struggling with reading characters from console in c++.
Here is what I tried to do:
char x;
char y;
char z;
cout<<"Please enter your string: ";
string s;
getline(cin,s);
istringstream is(s);
is>> x >> y >> z;
The problem is if the user enter something like this "1 20 100":
x will get 1
y will get 2
z will get 0... | You don't want to read characters but integers.
int x;
int y;
int z;
cout<<"Please enter your string: ";
string s;
getline(cin,s);
istringstream is(s);
is>> x >> y >> z;
|
2,557,664 | 2,557,803 | SDL doesn't detect Arrow Keys | I am working through the SDL tutorials over at http://lazyfoo.net/SDL_tutorials/index.php and I'm stuck on tutorial 8 where I'm working with key presses.
I'm using the following code:
//Our Main application loop
while(!quit){
if(SDL_PollEvent(&curEvents)){
if(curEvents.type == SDL_QUIT){
quit =... | I discovered the error which was not in the code posted above. The error was that for the arrow keypress messages, I used RenderText before the font was opened. By the time the posted code block was reached, font had already been opened and is the reason why that message shows.
|
2,557,729 | 2,557,733 | Formatted input in c++ | hey, i'm a noob to c++ (and coding in general)
i'm looking for an easy way to take two doubles (at once) from the keyboard and store them in a struct i've created called "Point" and then ultimately store the Point into a vector of Points that's a member of a class (called "Polygon").
i know i could do it with a scanf b... | You can do:
double d1,d2;
cin>>d1>>d2;
or you can directly read it into your structure variable as:
point p;
cin>>p.x>>p.y;
assuming your structure is defined something like:
struct point {
double x;
double y;
}
|
2,557,832 | 2,730,380 | Can't start gdb.exe in Qt Creator | I have a project in Qt Creator that builds fine, but when I try to debug it I get this message:
Adapter start failed
Unable to start gdb 'C:\Qt\2010.02.1\mingw\bin\gdb.exe':
Process failed to start: The directory name is invalid
If I navigate to the debug build folder and directly run my compiled application, it will... | Tools->Options->Debugger->Gdb
From
Gdb location you can set the path to your preferred GBD.
|
2,557,846 | 2,557,859 | Checking if parsed date is within a date range | So I am using a scripting language with c++-like syntax, and I am trying to think of the best way to check if a date is within range. The problem I am running into is that if the current day is in a new month, the check is failing.
Here is what my code looks like:
if(iMonth >= iStartMonth && iMonth <= iEndMonth)
{
... | You should really use boost::DateTime instead of attempting to rewrite the wheel (which when the wheel is a date/time framework it's not as trivial as it may seem). This only if the code you pasted is C++ and not your scripting language (it wasn't clear). Also may I suggest to use Lua instead? :)
Anyway the problem is... |
2,557,866 | 2,557,879 | Reallocating memory via "new" in C++ | Quick question regarding memory management in C++
If I do the following operation:
pointer = new char [strlen(someinput_input)+1];
And then perform it again, with perhaps a different result being returned from strlen(someinput_input).
Does this result in memory being left allocated from the previous "new" statement? A... | Every call to new must be matched with a corresponding call to delete.
As an aside, you should probably consider using std::string or even std::vector<char> (depending on the exact situation), rather than trying to allocate char arrays yourself. Then you don't ever need to worry.
|
2,557,950 | 2,557,961 | Why protected superclass member cannot be accessed in a subclass function when passed as an argument? | I get a compile error, which I'm slightly confused about. This is on VS2003.
error C2248: 'A::y' : cannot access protected member declared in class 'A'
class A
{
public:
A() : x(0), y(0) {}
protected:
int x;
int y;
};
class B : public A
{
public:
B() : A(), z(0) {}
B(const A& item) : A(), z(1) { x = item.y;}... | It's because of this:
class base_class
{
protected:
virtual void foo() { std::cout << "base::foo()" << std::endl; }
};
class A : public base_class
{
protected:
virtual void foo() { std::cout << "A::foo()" << std::endl; }
};
class B : public base_class
{
protected:
virtual void foo() { std::cout << "B::foo... |
2,558,153 | 2,558,161 | What is the underlying data structure of a STL set in C++? | I would like to know how a set is implemented in C++. If I were to implement my own set container without using the STL provided container, what would be the best way to go about this task?
I understand STL sets are based on the abstract data structure of a binary search tree. So what is the underlying data structure? ... | You could implement a binary search tree by first defining a Node struct:
struct Node
{
void *nodeData;
Node *leftChild;
Node *rightChild;
}
Then, you could define a root of the tree with another Node *rootNode;
The Wikipedia entry on Binary Search Tree has a pretty good example of how to implement an insert met... |
2,558,334 | 2,558,353 | a class function with if(this==NULL) test got compiled? | I saw this code snippet during our lab and it actually compiles in MSVC2008 and G++.
void LinkList< class T >::Insert(T n)
{
if (this == NULL)
// some code here
}
As far as I know the this must not be null since you cannot call a class functions in c++ if it wasn't instantiated. Is this a valid code? ... |
since you cannot call a class functions in c++ if it wasn't instantiated
The thing is, you can, but it leads to undefined behavior.
Such a check should probably be an assert, though such code isn't guaranteed to actually work by the standard. (If this is null, you're already in undefined behavior land.)
The reason i... |
2,558,610 | 2,558,618 | C question: no warning? | main()
{
printf("Hello World.");
}
Why does no warning is produced in gcc compiler even though we declare main() with return type 'int'
| Because you're not using the -Wall flag. When you do, you should get:
foo.c:1: warning: return type defaults to ‘int’
foo.c: In function ‘main’:
foo.c:1: warning: implicit declaration of function ‘printf’
foo.c:1: warning: incompatible implicit declaration of built-in function ‘printf’
foo.c:1: warning: control reache... |
2,558,613 | 2,559,017 | display multiple errors via bool flag c++ | Been a long night, but stuck on this and now am getting "segmentation fault" in my compiler..
Basically I'm trying to display all the errors (the cout) needed. If there is more than one error, I am to display all of them.
bool validMove(const Square board[BOARD_SIZE][BOARD_SIZE],
int x, int y, int value... | check your indices. As you are using a fixed sized array, it might be an off-by-one error
|
2,558,819 | 2,558,828 | regarding C++ stl container swap function | I recently learned that all stl containers have swap function:
i.e.
c1.swap(c2);
will lead to object underlying c1 being assigned to c2 and vice versa.
I asked my professor if same is true in case of c1 and c2 being references.
he said same mechanism is followed.
I wonder how it happens since c++ references cannot... | References are aliases. If you have two references, calling swap will swap what they are referring to, not the references themselves.
C& r1 = c1; // r1 references c1
C& r2 = c2; // r2 references c2
r1.swap(r2); // same as c1.swap(c2)
And it's not the variables that get swapped, it's what make them logically independe... |
2,559,026 | 2,559,060 | C++ error message output format | If I want to trigger an error in my interpreter I call this function:
Error( ErrorType type, ErrorSeverity severity, const char* msg, int line );
However, with that I can only output
Name error: Undefined variable in line 1
instead of
Name error: Undefined variable 'someVariableName' in line 1
I'm working entirely w... | This is C++, so you can overload your function with an extra parameter to provide the variable name. I would then use a std::stringstream to format the message. There is no need to worry about "efficiency" when reporting errors, as they should be rare and don't affect an application's overall performance.
|
2,559,193 | 2,559,241 | is there a way to condense a vector (C++)? | I have a sparsely populated vector that I populated via hashing, so elements are scattered randomly in the vector. Now what I want to do is iterate over every element in that vector. What I had in mind was essentially condensing the vector to fit the number of elements present, removing any empty spaces. Is there a way... | Either you save the additionally needed information during insertion of the elements (e.g. links to the previous / next element compared to a linked list) or you make one pass over all the elements and remove the unnecessary ones.
The first solution costs you some space (approx. 8 bytes / entry), the second costs you o... |
2,559,204 | 2,559,329 | Problems with making a simple Unix shell | I am trying to create a simple shell in Unix. I read a lot and found that everybody uses the strtok function a lot. But I want to do it without any special functions. So I wrote the code but I can't seem to get it to work. What am I doing wrong here?
void process(char**);
int arg_count;
char **splitcommand(char* input)... | The problem is with the
arg_count++;
inside the if(input[i] == ' ') and if(input[i] == '\0')
when you are parsing the command line and you find a space or you reach the end of the command line you are increment arg_count before you put a \0 at the end of the command you were reading.
So change it to:
if(... |
2,559,246 | 2,559,292 | boost::lambda expression doesn't compile | I tried to write a function that calculates a hamming distance between two codewords using the boost lambda library. I have the following code:
#include <iostream>
#include <numeric>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>
#include <boost/bind.hpp>
#include <boost... | First problem: when using boost/lambda, include <boost/lambda/bind.hpp> instead of <boost/bind.hpp>
Second problem: you need a using namespace boost::lambda after the #includes
still doesn't compile though
Edit:
Third problem - you need 6 arguments for std::inner_product, you're missing an initialization argument. pro... |
2,559,351 | 2,559,391 | Using Qt signals/slots instead of a worker thread | I am using Qt and wish to write a class that will perform some network-type operations, similar to FTP/HTTP. The class needs to connect to lots of machines, one after the other but I need the applications UI to stay (relatively) responsive during this process, so the user can cancel the operation, exit the application... | If you're doing a length job in the UI thread the UI is going to freeze. One way to avoid this is to call once in a while QCoreApplication::processEvents().
You should be VERY careful however to understand what this does before you decide to do it. Calling this function means that a GUI event can fire in the middle of ... |
2,559,357 | 2,559,462 | SHLoadImageFile(L"\\Program Files\\TrainingApp\\background.png"); whats that L in the argument for? | ive been working on c++ on linux for the past 2 years,and switched to windows c++ programming recently.
can anyone tell me what that L is there in the argument of the function:
SHLoadImageFile(L"\\Program Files\\TrainingApp\\background.png");
and on viewing certain sample code in MSVS C++ i came across hundereds of ty... | The L in the argument is standard way of telling the compiler that the following string literal is unicode not single-byte characters. It is equivalent to the postfix L to indicate that a long integer constant.
The windows typedefs do seem confusing but once you get your head around the naming scheme they start to make... |
2,559,676 | 2,559,718 | how to open many files simultaneously for reading in c | I'm trying to port some of my c++ code into c. I have the following construct
class reader{
private:
FILE *fp;
alot_of_data data;//updated by read_until() method
public:
reader(const char*filename)
read_until(some conditional dependent on the contents of the file, and the arg supplied)
}
Im then instantiating hund... | You create an abstract data type:
typedef struct {
FILE *fp;
alot_of_data data;//updated by read_until() method
} reader;
void init_reader(reader* that, const char* filename);
void read_until(reader* that, some conditional dependent on the contents of the file, and the arg supplied)
Then you can create and use o... |
2,559,681 | 2,562,393 | Qt -how to know whether content in child widgets has been changed? | In QMainWindow I have 2 QSplitters. In that splitters I have QTextEdit, QLineEdits, QTableWinget, Ragio buttons and so on... I want to know if somthing has been chaged after pressing File->New menu button. Is there any general method for doing this?
Somwhere I have read that it is recomended to use isWindowModified() f... | The isWindowModified() could be useful here since according to http://doc.trolltech.com/4.6/qwidget.html#windowModified-prop it propagates up to the parent.
However, I think you would need to set this yourself. For example, if you clicked the new button which leads to some text being inserted into a QTextEdit, you sti... |
2,559,724 | 2,577,363 | Unable to load libsctp.so for non root user | I have a Linux application that uses the libsctp.so library. When I run it as root, it runs fine.
But when I run it as an ordinary user, it gives the following error:
error while loading shared libraries: libsctp.so.1: cannot open shared object file: No such file or directory
But, when I do ldd as ordinary user, it ... | Fixed the problem. I added a new file in /etc/ld.so.conf.d with the followng name:
libsctp.so.1.conf
The contents of libsctp.so.1.conf is as follows:
/usr/local/lib/
And then ran
/sbin/ldconfig
, after which my app ran successfully.
Explanation: Since the setuid bit was set, the program is executed as root, for ... |
2,559,750 | 2,559,882 | private destructor for singleton class | Is it compulsory to have a private destructor for a singleton class.
| This might not be what you are looking for.. But for reference, I use it as follows:
// .h
class Foo {
public:
static Foo* getInstance();
static void destroy();
private:
Foo();
~Foo();
static Foo* myInstance;
};
// .cpp
Foo* Foo::myInstance = NULL;
Foo* Foo::getInstance(){
if (!myInstance){
... |
2,559,854 | 2,559,880 | Accessing subclass members from a baseclass pointer C++ | I have an array of custom class Student objects. CourseStudent and ResearchStudent both inherit from Student, and all the instances of Student are one or the other of these.
I have a function to go through the array, determine the subtype of each Student, then call subtype-specific member functions on them.
The problem... | You need a dynamic cast:
Student * s = new ...; // Create student of some sort.
if ( ResearchStudent * r = dynamic_cast<ReasearchStudent*>( s ) ) {
r->ResFunc();
}
else if ( CourseStudent * c = dynamic_cast<CourseStudent*>( s ) ) {
c->CourseFunc();
}
else {
throw "Unknown student type.";
}
Note that this ... |
2,559,896 | 2,559,902 | How are arrays passed? | Are arrays passed by default by ref or value?
Thanks.
| They are passed as pointers. This means that all information about the array size is lost. You would be much better advised to use std::vectors, which can be passed by value or by reference, as you choose, and which therefore retain all their information.
Here's an example of passing an array to a function. Note we hav... |
2,559,967 | 2,563,898 | Determining line orientation using vertex shaders | I want to be able to calculate the direction of a line to eye coordinates and store this value for every pixel on the line using a vertex and fragment shader. My idea was to calculate the direction gradient using atan2(Gy/Gx) after a modelview tranformation for each pair of vertices then quantize this value as a color ... |
How can I get access to the positions
of pairs of vertices?
You can't do that simply if you are just using a vertex and a fragment shader. Easy way is to use geometry shaders. Inside this shader stage you can have access to the pair of vertices that compose your line segment. Then it's straightforward to determine ... |
2,559,995 | 2,560,293 | Create an instance of an exported C++ class from Delphi | I followed an excellent article by Rudy Velthuis about using C++ classes in DLL's. Everything was golden, except that I need access to some classes that do not have corresponding factories in the C++ DLL. How can I construct an instance of a class in the DLL? The classes in question are defined as
class __declspec(d... | The correct way to do it is to write a wrapper DLL that exposes a factory for the class you need.
I am not sure hiw SWIG works, but anything that relies on reverse-engineering the name mangling seems a dubious approach.
Besides a C++ object should be created only in C++ code. You ought to leave the object creation sema... |
2,560,114 | 2,560,232 | Benchmarks used to test a C and C++ allocator? | Please kindly advise on benchmarks used to test a C and C++ allocator? Benchmarks satisfying any of the following aspects are considered:
Speed
Fragmentation
Concurrency
Thanks!
| If you ask about a general allocator for a C/C++ program then I have found this paper Hoard: A Scalable Memory Allocator for Multithreaded Applications which considers this question. This is a quote from this document
There is as yet no standard suite of
benchmarks for evaluating
multithreaded allocators. We know... |
2,560,172 | 2,560,307 | openssl crypto library - base64 conversion | I'm using openssl BIO objects to convert a binary string into a base64 string. The code is as follows:
void ToBase64(std::string & s_in) {
BIO * b_s = BIO_new( BIO_s_mem() );
BIO * b64_f = BIO_new( BIO_f_base64() );
b_s = BIO_push( b64_f , b_s);
std::cout << "IN::" << s_in.length();
BIO_write(b_s,... | You have two problems:
You need to call BIO_get_mem_data() on the mem bio - but you've lost the reference to it (you overwrite it with the return value from BIO_push, which is equal to b64_f).
You should call BIO_flush() on the base64 bio after you've written all your data to it.
|
2,560,214 | 2,560,236 | Returning an array of tm* structs from a function | Im trying to create an array of tm* structs, and then return them at the end of the function. This is what i have at the moment:
struct tm* BusinessLogicLayer::GetNoResponceTime()
{
struct tm* time_v[3];
struct tm* time_save;
int s = 3;
time_save = LastSavedTime();
time_v[0] = time_save;
sleep(5);
... | Either allocate the array on the heap, but you will need to remember to delete[] the array when you have finished using it.
tm* time_v = new tm[3];
Or as this is C++, a better option would be to use a vector
std::vector<tm> time_v(3);
The vector itself is allocated on the stack but it holds an array which is allocate... |
2,560,651 | 2,560,668 | Compile batch file into an EXE file | I want to compile a batch file into an EXE file using C++. I can get through parsing the batch file and writing a new .cpp file. But I don't know how to compile the new .cpp file into an EXE file for the end user.
OK, here's the thing, I am creating an application in DevC++ that will read in a batch file. Then, one by ... | Yes, you can provided that the end user has a C++ compiler installed and you're emitting valid C++.
Depending on the compiler you're using, your C++ executable would have to spawn a process that runs
cl main.cpp
or a similar invocation of the compiler after finishing the translation.
If your user doesn't have a compil... |
2,560,859 | 2,561,632 | Binding a pointer temporary to a reference | Please refer to the code below. In this code I am storing the const char* returned by test.c_str() into a reference. My question is - Will the data be correctly refering to the contents of test? I am thinking that the ptr returned by test.c_str() will be a temporary and if I bind it to a reference that reference will n... | If StoringClass needs a reference to a pointer, then you have to ensure that there is a pointer for it to refer to (and modify, since it's not a const reference), with a lifetime as long as that of the reference.:
#include <string>
#include <iostream>
template <typename T>
class StoringClass {
T& data;
public:
... |
2,561,139 | 2,566,598 | A variation of priority queue | I need some kind of priority queue to store pairs <key, value>. Values are unique, but keys aren't. I will be performing the following operations (most common first):
random insertion;
retrieving (and removing) all elements with the least key.
random removal (by value);
I can't use std::priority_queue because it only... | Ok, so I've tested many options and ended up with something based on the idea of Matthieu M.. I'm currently using a std::map<key_type, std::list<value_type> >, where the value_type contains a std::list<value_type>::iterator to itself, which is useful for removal.
Removal must check if the vector is empty, which implies... |
2,561,145 | 2,561,182 | Difference between boost::ref and regular references | What is the difference between boost::ref(i) and & i ? What are the situations where we cannot use regular references and have to go for boost::ref instead? Please include examples if possible.
| From the Boost.Ref Documentation:
The purpose of
boost::reference_wrapper is to
contain a reference to an object of
type T. It is primarily used to "feed"
references to function templates
(algorithms) that take their parameter
by value.
NB: An important difference between boost::reference_wrapper and std:... |
2,561,240 | 2,563,080 | C++ MFC server app with sockets crashes and I cannot find the fault, help! | My program has one dialog and two sockets. Both sockets are derived from CAsyncSocket, one is for listening, other is for receiving data from client. My program crashes when client tries to connect to server application and server needs to initialize receiving socket.
This is my MFC dialog class.
class CFileTransferSer... | I've looked into your code. The issue seems to be that you never call ListeningSocket::SetParentDlg(CFileTransferServerDlg* parent). Since you also do not initialize the m_pDlg pointer in the ListeningSocket constructor, it has random values and the program might crash here and there when you access this pointer. (I ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.