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 |
|---|---|---|---|---|
994,253 | 994,262 | Two classes that refer to each other | I'm new to C++, so this question may be basic:
I have two classes that need to refer to each other. Each is in its own header file, and #include's the other's header file. When I try to compile I get the error "ISO C++ forbids declaration of ‘Foo’ with no type" for one of the classes. If I switch things so the oppos... | You can use forward declarations in the header files to get around the circular dependencies as long as you don't have implementation dependencies in the headers. In Window.h, add this line:
class App;
In App.h, add this line:
class Window;
Add these lines before the class definitions.
Then in the source files, you ... |
994,288 | 994,357 | size_t vs int in C++ and/or C | Why is it that in C++ containers, it returns a size_type rather than an int? If we're creating our own structures, should we also be encouraged to use size_type?
| In general, size_t should be used whenever you are measuring the size of something. It is really strange that size_t is only required to represent between 0 and SIZE_MAX bytes and SIZE_MAX is only required to be 65,535...
The other interesting constraints from the C++ and C Standards are:
the return type of sizeof() i... |
994,353 | 994,428 | Static variable inside template function | In C++, if you define this function in header.hpp
void incAndShow()
{
static int myStaticVar = 0;
std::cout << ++myStaticVar << " " << std::endl;
}
and you include header.hpp in at least two .cpp files. Then you will have multiple definition of incAndShow(). Which is expected. However, if you add a template to the... | You can rely on this. The ODR (One Definition Rule) says at 3.2/5 in the Standard, where D stands for the non-static function template (cursive font by me)
If D is a template, and is defined in more than one translation unit, then the last four requirements from the list above shall apply to names from the template’s ... |
994,518 | 994,523 | Header file for functions inside of a namespace? | In C++ I have a file A.cpp that has the following in it:
namespace Foo {
bool Bar()
{
return true;
}
}
How would I declare this function in A.h? How do I handle the namespace?
| namespace Foo {
bool Bar();
}
|
994,593 | 994,623 | How to do an integer log2() in C++? | In the C++ standard libraries I found only a floating point log method. Now I use log to find the level of an index in a binary tree ( floor(2log(index)) ).
Code (C++):
int targetlevel = int(log(index)/log(2));
I am afraid that for some of the edge elements (the elements with value 2^n) log will return n-1.9999999999... | You can use this method instead:
int targetlevel = 0;
while (index >>= 1) ++targetlevel;
Note: this will modify index. If you need it unchanged, create another temporary int.
The corner case is when index is 0. You probably should check it separately and throw an exception or return an error if index == 0.
|
994,764 | 994,779 | Rounding doubles - .5 - sprintf | I'm using the following code for rounding to 2dp:
sprintf(temp,"%.2f",coef[i]); //coef[i] returns a double
It successfully rounds 6.666 to 6.67, but it doesn't work properly when rounding
5.555. It returns 5.55, whereas it should (at least in my opinion) return 5.56.
How can I get it to round up when the next digit i... | It seems you have to use math round function for correct rounding.
printf("%.2f %.2f\n", 5.555, round(5.555 * 100.)/100.);
This gives the following output on my machine:
5.55 5.56
|
994,905 | 994,937 | Is there ever a need for a "do {...} while ( )" loop? | Bjarne Stroustrup (C++ creator) once said that he avoids "do/while" loops, and prefers to write the code in terms of a "while" loop instead. [See quote below.]
Since hearing this, I have found this to be true. What are your thoughts? Is there an example where a "do/while" is much cleaner and easier to understand than... | Yes I agree that do while loops can be rewritten to a while loop, however I disagree that always using a while loop is better. do while always get run at least once and that is a very useful property (most typical example being input checking (from keyboard))
#include <stdio.h>
int main() {
char c;
do {
... |
994,907 | 994,963 | Passing a Safearray of custom types from C++ to C# | how can one use a Safearray to pass an array of custom types (a class containing only properties) from C++ to C#? Is using the VT_RECORD type the right way to do it?
I am trying in the following way, but SafeArrayPutElement returns an error when trying to fill the safearray the reference to the array of classes gets to... | I'm not really sure if I understand your question right, but maybe you need VT_DISPATCH?
I think if you want it to work with VT_RECORD, then your struct should actually be a struct (not a class) and also needs the [StructLayout(LayoutKind.Sequential)] attribute.
Edit: Can it be that the error you first got was DISP_E_B... |
994,949 | 995,287 | Specialize Function Templates vs Function Overload vs Class Specializing | According to this article from Herb Sutter, one should always pick Class Specializing over Function Overload and definitely over Specialized Function Templates.
The reason is that
Specializations don't overload. Overload resolution only selects a base template (or a nontemplate function, if one is available). Only... | The problem with explicitly specialising a function template only applies if the function is also overloaded:
template <typename T> void foo (T*); // #1
template <typename T> void foo (T); // #2
template <> void foo<int*> (int*);
int main () {
int * i;
foo (i); // Calls #1 not specialization of #2
}
Withou... |
995,253 | 995,311 | How to compile the Botan crypto library as a static lib in VC++? | I've been extremely unsuccessful in compiling Botan as a static library in Visual C++. The build.h file contains the following code:
#ifndef BOTAN_DLL
#define BOTAN_DLL __declspec(dllexport)
#endif
This macro then shows up pretty much everywhere in the Botan codebase, like this:
class BOTAN_DLL AutoSeeded_RNG : publ... | What are the first few error messages you get? Maybe you have forgotten a header file include?
It looks like maybe your compilation command is wrong:
cl.exe /Ibuild\include /O2 /EHsc /GR /D_CONSOLE /D "BOTAN_DLL" /nologo
/c src\checksum\adler32\adler32.cpp /Fobuild\lib\adler32.obj
I think you incorrectly have a spa... |
995,314 | 995,330 | boost::bind and class member function | Consider following example.
#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/bind.hpp>
void
func(int e, int x) {
std::cerr << "x is " << x << std::endl;
std::cerr << "e is " << e << std::endl;
}
struct foo {
std::vector<int> v;
void calc(int x) {
std::for_each(v.beg... | You were really, really close:
void calc(int x) {
std::for_each(v.begin(), v.end(),
boost::bind(&foo::func2, this, _1, x));
}
EDIT: oops, so was I. heh.
Although, on reflection, there is nothing really wrong with your first working example. You should really favour free functions over member functions wher... |
995,434 | 995,456 | Arrays of strings in Managed C++ | I'm trying to write an application in Managed C++, but I cannot work out how to declare an array of strings.
String^ linet[];
throws an error
'System::String ^' : a native array cannot contain this managed type
So I suppose there's a different way to do this for managed data types. What exactly is it?
| Do you really mean Managed C++? Not C++/CLI?
Assuming you're actually using C++/CLI (because of the error message you posted), there are two ways to do this:
array<String^>^ managedArray = gcnew array<String^>(10);
will create a managed array, i.e. the same type as string[] in C#.
gcroot<String^>[] unmanagedArray;
wi... |
995,902 | 26,982,335 | Unable to find the location of C++'s standard libraries in OS/X? | I have looked at /System/Library, but I have not found the iostream library/module by
ack iostream
Where are the standard libraries in OS/X?
| On OS X 10.10 Yosemite, they're located here:
/usr/include/c++
|
996,135 | 996,154 | How are Java generics different from C++ templates? Why can't I use int as a parameter? | I am trying to create
ArrayList<int> myList = new ArrayList<int>();
in Java but that does not work.
Can someone explain why int as type parameter does not work?
Using Integer class for int primitive works, but can someone explain why int is not accepted?
Java version 1.6
| Java generics are so different from C++ templates that I am not going to try to list the differences here. (See What are the differences between “generic” types in C++ and Java? for more details.)
In this particular case, the problem is that you cannot use primitives as generic type parameters (see JLS §4.5.1: "Type ar... |
996,200 | 996,251 | Is there a right way to return a new object instance by reference in C++? | So I was writing some code, and I had something like this:
class Box
{
private:
float x, y, w, h;
public:
//...
Rectangle & GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
};
Then later in some code:
Rectangle rect = theBox.GetRect();
Which worked in my debug build, but ... | You can't return a reference to a temporary object on the stack. You have three options:
Return it by value
Return by reference via a pointer to something that you created on the heap with the new operator.
Return by reference what you received by reference as an argument. [EDIT: Thanks to @harshath.jr for pointing th... |
996,844 | 996,868 | C++ shift operator precedence weirdness | Consider the following code:
typedef vector<int> intVec;
intVec& operator<<(intVec& dst, const int i) {
dst.push_back(i);
return dst;
}
int intResult0() {
return 23;
}
int intResult1() {
return 42;
}
// main
intVec v;
v << intResult0() << intResult1();
The weird thing is, that the compiler generates ... | According to Stroustrup section 6.2.2:
The order of evaluation of
subexpressions within an expression is
undefined.
|
997,018 | 997,137 | JNI Call to Authenticate user using LogonUser? | C++ noob here wonding how i can authenticate a Windows User via Java servlet.
Here is the code i have put together to take in a JNI call from my java servlet with the user's username domain and password:
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include "Validate.h"
JNIEXP... | That your compiler couldn't find LogonUser suggests that you're missing the windows headers. Include windows.h
Also, the generic windows handle type is spelled HANDLE, all in caps.
See the LogonUser docs for more details.
|
997,117 | 997,251 | How to make configure script check the dependencies | I generated a configure script with autoconf to build my project.
It works fine unless I don't have some needed library installed. Make returns error when lacking some files, but it should be actually checked by the configure script i think?
So my question is: How to modify an autoconf generated script to seek for depe... | Depends on the dependency, there is no generic solution.
There are AC_CHECK_LIB and AC_SEARCH_LIBS macros that may work for you if the libraries and headers are installed in standard locations.
Many packages nowadays support pkg-config or something similar which allows you to check for existence of libraries, and also ... |
997,232 | 997,264 | CRC error-correction library? | Is there a CRC library that enables the user not only detect errors but also correct them? I'm looking for a C/C++ or Java library, ideally open-source.
| I believe that CRCs can only detect errors, not correct them. That's certainly true of the most common implementation. You want some kind of error correction technique, not a CRC. I'm not aware of any libraries for doing this, but they must be easy enough to find once you know what you're looking for.
|
997,250 | 1,002,825 | Property Pages (Wizard) - OnQueryCancel | I am trying to handle the 'Cancel' button in my property pages (wizard) and I've implemented the 'OnQueryCancel' function to catch the cancel message successfully, but unfortunately it seems that the 'OnQueryCancel' function is being called twice if the user clicked the cancel button. Any ideas on how I could address t... | My first guess is that you have directly sunk the "query cancel" message (is that a message?) or maybe you have a click handler on the button itself AND it is called automatically on click of the cancel button. Try commenting out your message map entry.
Try creating a new project with classwizard and compare.
|
997,366 | 997,914 | C++/GLFW - The right way to use Mutex objects? | I'm working on a simulation that uses multithreading extensively. The thing is that, until now i've never used any mutex objects to protect my data. And the result, is that i'm getting bunch of segmentation faults..
I'm trying to lock/unlock with mutex while : reading/writing but that causes me another segfault :
#0 7... | You could wrap your containers which will make your code easier to understand:
template<typename T>
class MultithreadedVector
{
public:
void pushback( T data )
{
glfwLockMutex(m_mutex);
m_container.push_back( data );
glfwUnlockMutex(m_mutex);
}
//then similar for erase etc
private:
... |
997,498 | 997,582 | Poker code cleanup modification from book...not quite right | Working through more book examples- this one is a partial poker program-
This segment deals with straight hand....
First what was given- only relevant parts....will provide entire code if needed...
int suits[5]; //index 1..4- value start at 1
int values[14]; //index 1..13- value same as rank, A = 1, K = 13
cin.get(ran... | EDIT: I figured I'd would first answer your question directly. Lets first clear up how the original algorithm worked. Basically it loops from 1 to 13, and each time it sees a card in that slot, it adds to count. If anything ever breaks the sequence, it resets the counter. Finally, if the counter reaches 5, you have a s... |
997,512 | 997,531 | String representation of time_t? | time_t seconds;
time(&seconds);
cout << seconds << endl;
This gives me a timestamp. How can I get that epoch date into a string?
std::string s = seconds;
does not work
| Try std::stringstream.
#include <string>
#include <sstream>
std::stringstream ss;
ss << seconds;
std::string ts = ss.str();
A nice wrapper around the above technique is Boost's lexical_cast:
#include <boost/lexical_cast.hpp>
#include <string>
std::string ts = boost::lexical_cast<std::string>(seconds);
And for quest... |
997,602 | 997,666 | Link error "LogonUser" compiling C++ program? | Hey Folks i am trying to compile this C++ program:
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <Windows.h>
#include "Validate.h"
JNIEXPORT jstring JNICALL Java_Validate_takeInfo(JNIEnv *env, jobject obj,
jstring domain, jstring id, jstring idca, jstring passwo... | MSDN says that LogonUser is in Advapi32.lib. It looks like the problem is that you're not including Advapi32.lib. LIBPATH affects where the linker searches for libraries, not what libraries the linker searches for, and nowhere are you telling the linker to search for Advapi32.dll.
On Visual C++ 2008, you should be ab... |
997,620 | 997,796 | How do I take a DIB and convert it to a tif using libtiff | I am trying to read in a scanned image and compress it from a DIB in memory into a TIF file. I am using the libtiff library and have found a couple examples online but none of them really do as I need them to. I need to take the image from the DIB and turn it into a B&W image.
Here is the code I have modified from an o... | I may be wrong, but I think that for CCITTFAX4 encoding libtiff expects eight pixels per byte, padded to the end of the byte if the image width is not divisible by 8.
If the width of the image is 150, for example, the scanline should be 19 bytes, not 150.
There is a good example of using libtiff here, though it does n... |
997,821 | 997,855 | How to make a function return a pointer to a function? (C++) | I'm trying to make a function that takes a character, then returns a pointer to a function depending on what the character was. I just am not sure how to make a function return a pointer to a function.
| #include <iostream>
using namespace std;
int f1() {
return 1;
}
int f2() {
return 2;
}
typedef int (*fptr)();
fptr f( char c ) {
if ( c == '1' ) {
return f1;
}
else {
return f2;
}
}
int main() {
char c = '1';
fptr fp = f( c );
cout << fp() << endl;
}
|
997,925 | 998,236 | How to buffer data for send() and select()? | While a send() succeeds with all data being sent most of the time, it is not always the case. Thus people are advised to use the write-fdset for select() and poll() to check when the socket is writeable.
How do usual mechanisms look like to actually buffer the data to send while still maintaining a well comprehensible ... | As we're in C++ land, you could store the data in a std::vector
New data gets appended to the end of the vector. When you get notification that the socket is writable, try to send the complete vector. send() will return how much was really sent. Then simply erase that number of bytes from the beginning of the vector:
s... |
997,946 | 27,856,440 | How to get current time and date in C++? | Is there a cross-platform way to get the current date and time in C++?
| Since C++ 11 you can use std::chrono::system_clock::now()
Example (copied from en.cppreference.com):
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono... |
998,072 | 1,210,290 | Tee-ing input (cin) out to a log file (or clog) | I am looking for a way to branch (tee) the input read from an istream (cin, in my case) out to a log file (clog/ofstream/etc), while still using the input for processing.
I have read about boost::tee_device, and it is very similar to my requirements. Unfortunately, it is implemented as an ostream, and thus solves a si... | Final Answer:
#ifndef TEE_ISTREAM_H_
#define TEE_ISTREAM_H_
/*****************************************************************************/
#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/invert.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boos... |
998,162 | 998,191 | Is it possible to disable stderr in C++? | I wrote a program for linux using libxml2 for html parsing. Although it does its job, the html parser writes lots of various errors to stderr. Is it possible to disable stderr at all (or redirect it to /dev/null while not having to run it with a redirecting shell script)? I can live with having to write my own errors t... | Use freopen to redirect to dev/null:
freopen("/dev/null", "w", stderr);
|
998,247 | 998,269 | Are static fields inherited? | When static members are inherited, are they static for the entire hierarchy, or just that class, i.e.:
class SomeClass
{
public:
SomeClass(){total++;}
static int total;
};
class SomeDerivedClass: public SomeClass
{
public:
SomeDerivedClass(){total++;}
};
int main()
{
SomeClass A;
SomeClass B;
... | 3 in all cases, since the static int total inherited by SomeDerivedClass is exactly the one in SomeClass, not a distinct variable.
Edit: actually 4 in all cases, as @ejames spotted and pointed out in his answer, which see.
Edit: the code in the second question is missing the int in both cases, but adding it makes it OK... |
998,248 | 998,253 | How can I stop g++ from linking unwanted exception-handling code? | I'm developing an embedded application using GCC/G++ compiled for arm-eabi. Due to resource constraints, I'm trying to disable the standard C++ exception handling. I'm compiling the code with "-fno-exceptions
-nostartfiles -ffreestanding".
When a global instance of a class exists, and that class contains an instance... | I think the closest you can get is compiling and linking with -fno-exceptions and -fno-rtti. If there's a better way to get rid of the rest, I'd be glad to hear it myself.
As far as getting rid of new, try -nostdlib.
|
998,311 | 998,418 | How to declare two different static variables? (C++) | EDIT: declaring them private was a typo, I fixed it:
Relating to another question, if I declared a static variable in a class, then derived a class from that, is there any way to declare the static variable as individual per each class. Ie:
class A:
{
public:
static int x;
};
class B:A
{
public:
const static int x;
};... | When you're using static variables, it might be a good idea to refer to them explicitly:
public class B:A
{
public const static int x;
public int foo()
{
return B::x;
}
}
That way, even if the class "above" yours in the hierarchy decides to create a similarly-named member, it won't break your code. Likewi... |
998,425 | 998,457 | Why does const imply internal linkage in C++, when it doesn't in C? | See subject. What were they thinking?
UPDATE: Changed from "static" to "internal linkage" to save confusion.
To give an example... Putting the following in a file:
const int var_a = 1;
int var_b = 1;
...and compiling with g++ -c test.cpp only exports var_b.
| I believe you mean
Why does const imply internal linkage in C++
It's true that if you declare a const object at namespace scope, then it has internal linkage.
Appendix C (C++11, C.1.2) gives the rationale
Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal... |
998,429 | 998,478 | OpenCV: Accessing And Taking The Square Root Of Pixels | I'm using OpenCV for object detection and one of the operations I would like to be able to perform is a per-pixel square root. I imagine the loop would be something like:
IplImage* img_;
...
for (int y = 0; y < img_->height; y++) {
for(int x = 0; x < img_->width; x++) {
// Take pixel square root here
}
}
My qu... | Assuming img_ is of type IplImage, and assuming 16 bit unsigned integer data, I would say
unsigned short pixel_value = ((unsigned short *)&(img_->imageData[img_->widthStep * y]))[x];
See also here for IplImage definition.
|
998,571 | 998,686 | C++ Template for safe integer casts | I am trying to write a C++ template function that will throw a runtime exception on integer overflow in casts between different integral types, with different widths, and possible signed/unsigned mismatch. For these purposes I'm not concerned with casting from floating-point types to integral types, nor other object-to... | Have you tried SafeInt? It's a cross platform template that will do integer overflow checks for a variety of integer types. It's available on github
https://github.com/dcleblanc/SafeInt
|
999,120 | 999,218 | C++ "hello world" Boost tee example program | The Boost C++ library has Function Template tee
The class templates tee_filter and tee_device provide two ways to split an output sequence
so that all data is directed simultaneously to two different locations.
I am looking for a complete C++ example using Boost tee to output to standard out and to a file like "sam... | Based on help from the question John linked:
#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include <iostream>
using std::ostream;
using std::ofstream;
using std::cout;
namespace bio = boost::iostreams;
using bio::tee_device;
using bio::stream;
int main()
{
typedef t... |
999,303 | 1,000,048 | Qt: Custom widget in QScrollArea | I am attempting to create a custom widget. My Widget renders itself unless it is inside a scroll area. The code below works. If I change the if(0) to an if(1) inside the MainWindow constructor, it will not render the "Hello World" string. I assume that I must (re)implement some additional methods, but so far I have not... | You just have to give your HelloWidget a size and place.
Add this line to your code.
hello->setGeometry(QRect(110, 80, 120, 80));
Or if you want to fill the scroll area with your widget:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QScrollArea *const scroll(new QScrollArea);
QHBoxLayout *... |
999,340 | 999,353 | Question about pure virtual destructor | If we define a abstract class which has a pure virtual destructor, why do we have to give a definition of a destructor in the abstract class?
| The destructor for the base class must be called when the object is destroyed, so it needs a definition.
|
999,358 | 999,383 | "Undefined symbols" linker error with simple template class | Been away from C++ for a few years and am getting a linker error from the following code:
Gene.h
#ifndef GENE_H_INCLUDED
#define GENE_H_INCLUDED
template <typename T>
class Gene {
public:
T getValue();
void setValue(T value);
void setRange(T min, T max);
private:
T value;
T minValue;
T... | The template definition (the cpp file in your code) has to be included prior to instantiating a given template class, so you either have to include function definitions in the header, or #include the cpp file prior to using the class (or do explicit instantiations if you have a limited number of them).
|
999,371 | 999,400 | Container of pointers | I'm having some trouble in declaring a STL Set of pointers to class instances. More specifically, I have this scenario:
class SimulatedDiskFile {
private:
// ...
public:
// ...
struct comparator {
bool operator () (SimulatedDiskFile* const& file_1, SimulatedDiskFile* const& file_2) {
retur... | Fixing a few glitches,
#include <set>
class SimulatedDiskFile {
public:
int getFileName() { return 23; }
struct comparator {
bool operator () (SimulatedDiskFile* file_1, SimulatedDiskFile* file_2) {
return (file_1->getFileName() < file_2->getFileName());
}
};
};
typedef std::set<Sim... |
999,699 | 999,717 | Thread Safe Data and Thread Safe Containers | Hi Guys I want to know what is the difference between thread safe Data and Thread Safe Containers
| Thread safe data:
Generally refers to data which is protected using mutexes, semaphores or other similar constructs.
Data is considered thread safe if measures have been put in place to ensure that:
It can be modified from multiple threads in a controlled manner, to ensure the resultant data structure doesn't becomin... |
999,727 | 999,734 | Cannot convert from 'const wchar_t *' to '_TCHAR *' | _TCHAR* strGroupName = NULL;
const _TCHAR* strTempName = NULL;
//Assign some value to strTempName
strGroupName = _tcschr(strTempName, 92) //C2440
I get an error at the above line while compiling this code in VS2008. In VC6 it compiles fine.
Error C2440: '=' : cannot convert from
'const wchar_t *' to '_TCHAR *'
W... | Try casting it as
strGroupName = (_TCHAR*)_tcschr(strTempName, 92);
Seems to me that VS2008 got a little more strict on type casts, and won't automatically do them in some cases.
|
1,000,167 | 1,000,198 | Error C2593: Operator = is ambiguous | typedef map<wstring , IWString> REVERSETAG_CACHE ;
REVERSETAG_CACHE::iterator revrsetagcacheiter;
.
.
.
wstring strCurTag;
strCurTag = revrsetagcacheiter->second; //Error C2593
Error C2593: Operator = is ambiguous
Why does the above assignment give this error? It works in VC6. Does not compile in VC9.
| revrsetagcacheiter->second is of type IWString .
Hence it won't compile. I don't think it will compile in VC6 also.
I'll try one final time: Is your BasicString class c_str() method ? If so try converting it to wstring using std::wstring str(iter->second.c_str());
|
1,000,303 | 1,000,320 | Is there a faster way to detect object type at runtime than using dynamic_cast? | I have a hierarchy of types - GenericClass and a number of derived classes, InterestingDerivedClass included, GenericClass is polymorphic. There's an interface
interface ICallback {
virtual void DoStuff( GenericClass* ) = 0;
};
which I need to implement. Then I want to detect the case when GenericClass* pointer pa... | I always look on the use of dynamic_cast as a code smell. You can replace it in all circumstances with polymorphic behaviour and improve your code quality. In your example I would do something like this:
class GenericClass
{
virtual void DoStuff()
{
// do interesting stuff here
}
};
class InterestingDerivedC... |
1,000,343 | 1,051,256 | Boost serialization problem | i have situation like this:
class IData
{
virtual void get() = 0;
virtual void set() = 0;
}
BOOST_ASSUME_IS_ABSTRACT(IData)
BOOST_EXPORT_CLASS(IData)
template<typename T>
class ConcreteData : public IData
{
public:
protected:
template<typename Archive>
void serialize(Archive& ar, const unsigned version)
{
... | Try using BOOST_CLASS_EXPORT_GUID instead:
BOOST_CLASS_EXPORT_GUID(ConcreteData<float>, "ConcreteData<float>")
BOOST_CLASS_EXPORT_GUID(ConcreteData<int>, "ConcreteData<int>")
|
1,000,577 | 4,790,981 | Can I stop COM from swallowing uncaught C++ exceptions in the callee process? | I am maintaining a project which uses inter-process COM with C++. At the top level of the callee functions there are try/catch statements directly before the return back through COM. The catch converts any C++ exceptions into custom error codes that are passed back to the caller through the COM layer.
For the purpose... | This just in, a year and a half after the question was asked -
Raymond Chen has written a post about "How to turn off the exception handler that COM 'helpfully' wraps around your server". Seems like the ultimate answer to the question. If not for the OP, for future readers.
|
1,000,663 | 1,000,672 | Using a C++ class member function as a C callback function | I have a C library that needs a callback function to be registered to customize some processing. Type of the callback function is int a(int *, int *).
I am writing C++ code similar to the following and try to register a C++ class function as the callback function:
class A {
public:
A();
~A();
int e(int *k, i... | You can do that if the member function is static.
Non-static member functions of class A have an implicit first parameter of type class A* which corresponds to this pointer. That's why you could only register them if the signature of the callback also had the first parameter of class A* type.
|
1,000,908 | 15,445,167 | Is it possible to forbid deriving from a class at compile time? | I have a value class according to the description in "C++ Coding Standards", Item 32. In short, that means it provides value semantics and does not have any virtual methods.
I don't want a class to derive from this class. Beside others, one reason is that it has a public nonvirtual destructor. But a base class should h... | Even if the question is not marked for C++11, for people who get here it should be mentioned that C++11 supports new contextual identifier final. See wiki page
|
1,001,067 | 1,001,117 | STL string comparison functor | I have the following functor:
class ComparatorClass {
public:
bool operator () (SimulatedDiskFile * file_1, SimulatedDiskFile * file_2) {
string file_1_name = file_1->getFileName();
string file_2_name = file_2->getFileName();
cout << file_1_name << " and " << file_2_name << ": ";
if (fil... | There's nothing wrong with the code you've posted, functionally speaking. Here's a complete test program - I've only filled in the blanks, not changing your code at all.
#include <iostream>
#include <string>
#include <set>
using namespace std;
class SimulatedDiskFile
{
public:
string getFileName() { return name; ... |
1,001,154 | 1,001,186 | Using a namespace twice | In c++ Is it OK to include same namespace twice?
compiler wont give any error but still will it affect in anyway
Thanks,
EDIT:
I meant
using namespace std;
// . . STUFF
using namespace std;
| It depends what you mean by 'include'. Saying:
using namespace std;
...
using namespace std:
is OK. But saying:
namespace X {
...
namespace X {
would create a nested namespace called X::X, which is probably not what you wanted.
|
1,001,375 | 1,001,413 | C++ - Undefined reference to a class recently created ! | I just created this new class :
//------------------------------------------------------------------------------
#ifndef MULTITHREADEDVECTOR_H
#define MULTITHREADEDVECTOR_H
//------------------------------------------------------------------------------
#include <vector>
#include <GL/GLFW.h>
//-------------------------... | That's what will happen when blindly moving a class template implementation to a cpp file.
To make that work, you must know exactly for what types of T you will instantiate the class template and specify them in the cpp file.
In this case, put this in the cpp file:
template class MultithreadedVector<Vehicle>;
Note tha... |
1,001,420 | 1,001,428 | How to define a function with same name which is present in different file | I want to define a class like this
class HttpRestAccessor
{
public:
IResource& UpdateResource(string& , IResource& );
};
and implementing in cpp file
IResource& HttpRestAccessor::UpdateResource(string& resourceUri, IResource& resource)
this cpp file refers to Winbase.h which has defined UpdateResource as follows
... | Macro's totally ignore scope.
Basically the pre-precessor will do a find/replace of UpdateResource with UpdateResourceW so you're all out of luck.
renaming the method is your only option
|
1,001,522 | 1,001,682 | Pointers in C# and how frequently it is used in the application? | For me , the Pointer was one of the hardest concept in programming languages in C++. When I was learning C++, I spent tremendous amount of time learning it. However, Now I primarily work in projects that are entirely written in languages like C#, and VB.NET etc. As a matter fact, I have NOT touched C++ for almost 4 ye... | Personally, I've never had a need for using pointers in .NET, but if you're dealing with absolute performance critical code, you'd use pointers. If you look at the System.String class, you'll see that a lot of the methods that handle the string manipulation, use pointers. Also, when dealing with image processing, very ... |
1,001,535 | 1,001,576 | Linking C++ code with 'gcc' (without g++) | Hi all: quick question: I'm in a situation where it would be useful to generate my C++ executable using only 'gcc' (without g++). Reason for this is that I have to submit the code to an automatic submission server which doesn't recognize the 'g++' (or 'c++', for that matter) command.
In my experiments, while I'm compil... | You can link the standard c++ library with the -l flag to gcc:
gcc cplusplus.o -lstdc++ -o myexe
|
1,001,544 | 1,001,645 | Options for a message passing system for a game | I'm working on an RTS game in C++ targeted at handheld hardware (Pandora). For reference, the Pandora has a single ARM processor at ~600Mhz and runs Linux. We're trying to settle on a good message passing system (both internal and external), and this is new territory for me.
It may help to give an example of a messag... | The network will be using locking as well. It will just be where you cannot see it, in the OS kernel.
What I would do is create your own message queue object that you can rewrite as you need to. Start simple and make it better as needed. That way you can make it use any implementation you like behind the scenes witho... |
1,001,719 | 1,109,888 | Detecting AC Power connection in WinPE? | I'm trying to determine if a laptop is connected to AC power.
The OS Im running under is WinPE.
My app is written in native C++.
WMI queries using Win32_Battery are not supported and the GetSystemPowerStatus API always returns '1' for ACLineStatus (running on AC power or not).
Any ideas?
Additonal investigation:
Just ... | I managed to answer my own question and it proved to be very simple in the end.
In WinPE the following noddy script returned null when executed because the battery wasn't being recognised:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuer... |
1,002,024 | 1,002,071 | Sorting two linked lists according to memory location | I need to merge two doubly-linked lists, but not by their values (the lists are not sorted).
I want to obtain a single list that has all the nodes from the two, but in the order in which they appear in memory.
Maybe this image helps more:
http://img140.imageshack.us/i/drawing2.png/
Is there any algorithm (preferably a ... | Well it sounds like you aren't using std::list, so I'll go with the generic solution. Since your requirement is to merge the lists, but have the nodes be in order of there physical location in memory. You can likely just append the two lists, then sort the nodes by address of the nodes.
see: http://www.chiark.greenend.... |
1,002,064 | 1,002,293 | Screen capture from windows service | I've got DirectShow based screen capture software. Internally it calls CopyScreenToBitmap function to grab screen. Then the picture is compressed by ffdshow.
It works fine as a desktop application, but as window service, on certain computers it does not work (black picture). I've set 'Allow service to interact with des... | Try this in addition to allowing access to the desktop:
Enumerate all Window Stations: EnumWindowStations
Find the window station for the logged on user, and make it your process' window station: SetProcessWindowStation - see example in this thread
Then set the desktop for your current thread to the default desktop o... |
1,002,164 | 1,571,635 | Write applications in C or C++ for Android? | I'm trying to develop/port a game to Android, but it's in C, and Android supports Java, but I'm sure there must be a way to get a C app on there, anyone knows of a way to accomplish this?
| For anyone coming to this via Google, note that starting from SDK 1.6 Android now has an official native SDK.
You can download the Android NDK (Native Development Kit) from here:
https://developer.android.com/ndk/downloads/index.html
Also there is an blog post about the NDK:
http://android-developers.blogspot.com/200... |
1,002,503 | 1,002,521 | How is C++'s multiple inheritance implemented? | Single inheritance is easy to implement. For example, in C, the inheritance can be simulated as:
struct Base { int a; }
struct Descendant { Base parent; int b; }
But with multiple inheritance, the compiler has to arrange multiple parents inside newly constructed class. How is it done?
The problem I see arising is: sho... | The following paper from the creator of C++ describes a possible implementation of multiple inheritance:
Multiple Inheritance for C++ - Bjarne Stroustrup
|
1,002,543 | 1,009,245 | How can I capture output from the Windows cmd shell? | Is there any way with, say Perl or PHP, that I can grab output from another process that outputs to the Windows cmd shell? I have a game server that outputs certain information, for example say 'player finished track in 43s' and I want to grab that line and use Perl or PHP to send a request to a webserver to update ran... | You need to start your server within Perl:
my $server_out = `server.exe`; # Note the backticks.
Now $server_out contains the output of server.exe. But the trick here is that you have to wait until server.exe exits to get the out put.
Try IPC::Run (which is not a core module)
use English;
use IPC::Run;
my ($stdout, $st... |
1,002,587 | 1,002,746 | Can I use the Curiously Recurring Template Pattern here (C++)? | I have a C++ application that can be simplified to something like this:
class AbstractWidget {
public:
virtual ~AbstractWidget() {}
virtual void foo() {}
virtual void bar() {}
// (other virtual methods)
};
class WidgetCollection {
private:
vector<AbstractWidget*> widgets;
public:
void addWidget(Abstrac... | CRTP or compile-time polymorphism is for when you know all of your types at compile time. As long as you're using addWidget to collect a list of widgets at runtime and as long as fooAll and barAll then have to handle members of that homogenous list of widgets at runtime, you have to be able to handle different types a... |
1,002,998 | 1,003,006 | What Windows C++ IDEs support the new C++0X standard? | What are excellent C++ IDE options that support the new standard c++0x (windows os friendly) besides visual .net 2010 (the beta is way too slow/clunky)?
| While not supporting the full C++0x standard, much of the TR1 stuff is included in the SP1 update to Visual Studio 2008. The SP1 update includes the feature pack that was released last year.
|
1,003,190 | 1,003,243 | Not locking mutex for pthread_cond_timedwait and pthread_cond_signal ( on Linux ) | Is there any downside to calling pthread_cond_timedwait without taking a lock on the associated mutex first, and also not taking a mutex lock when calling pthread_cond_signal ?
In my case there is really no condition to check, I want a behavior very similar to Java wait(long) and notify().
According to the documentati... | The first is not OK:
The pthread_cond_timedwait() and
pthread_cond_wait() functions shall
block on a condition variable. They
shall be called with mutex locked by
the calling thread or undefined
behavior results.
http://opengroup.org/onlinepubs/009695399/functions/pthread_cond_timedwait.html
The reason is t... |
1,003,309 | 1,003,671 | What exactly does C++ profiling (google cpu perf tools) measure? | I trying to get started with Google Perf Tools to profile some CPU intensive applications. It's a statistical calculation that dumps each step to a file using `ofstream'. I'm not a C++ expert so I'm having troubling finding the bottleneck. My first pass gives results:
Total: 857 samples
357 41.7% 41.7% 35... | From my comments:
The numbers you get from your profiler say, that the program should be around 40% faster without the print statements.
The runtime, however, stays nearly the same.
Obviously one of the measurements must be wrong. That means you have to do more and better measurements.
First I suggest starting with ano... |
1,003,360 | 1,033,337 | Complete C++ i18n gettext() "hello world" example | I am looking for a complete i18n gettext() hello world example. I have started a script based upon A tutorial on Native Language Support using GNU gettext by G. Mohanty. I am using Linux and G++.
Code:
cat >hellogt.cxx <<EOF
// hellogt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
#include <cstdlib>
... | cat >hellogt.cxx <<EOF
// hellogt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
int main (){
setlocale(LC_ALL, "");
bindtextdomain("hellogt", ".");
textdomain( "hellogt");
std::cout << gettext("hello, world!") << std::endl;
}
EOF
g++ -o hellogt hellogt.cxx
xgettext --package-name hell... |
1,003,497 | 1,003,579 | How to remove black background from textures in OpenGL | I'm looking for a way to remove the background of a 24bit bitmap, while keeping the main image totally opaque, up until now blending has served the purpose but now I need to keep the main bit opaque. I've searched on Google but found nothing helpful, I think I'm probably searching for the wrong terms though, so any hel... | When you are creating the texture for OpenGL, you'll want to create the texture as a 32-bit RGBA texture. Create a buffer to hold the contents of this new 32-bit texture and iterate through your 24-bit bitmap. Every time you come across your background color, set the alpha to zero in your new 32-bit bitmap.
struct Co... |
1,003,905 | 1,005,445 | "Smart" Linked Scrollbar and Edit Controls? | I hope that I can explain my problem well enough for someone to help.
Basically, I have a horizontal scrollbar (ranged 0 to 1000) and an edit control that represents the position of the scrollbar divided by 1000, so that the user can use either the scrollbar to select a range of numbers between 0 and 1 up to a 3 decima... | With the first approach, it looks like you're almost there: the only really significant problem is that the repeated calls to UpdateData() mess with the cursor position as the user is typing.
Given that you're trying to have a reasonably complex interaction between the controls, what I'd suggest is not to do validation... |
1,003,956 | 1,100,876 | Browser Helper Object UI | I am a newbie working towards developing an IE extension that would appear as an overlay in certain webpages. I am getting started by creating a simple BHO in VS2008 (using C++), but I am wondering how UI may be incorporated within the project. Any ideas?
Just to give you an idea, I'm looking for overlays similar to wh... | Using CreateWIndowEx() was what I was looking for :)
|
1,003,987 | 1,004,063 | Borland c++ version 0.7 is it still available? | My cousin is actually asking me if it's still available but I can't find that version, since it's too old, he's complaining about version 5.5 saying that it doesn't recognize his libraries. Is there any link? I doubt but I thought I'll give it a shot. 0.7 is way too old I know
| The tools division of Borland was spun out into a separate division called CodeGear. CodeGear was subsequently bought by Embarcadero. On their website they have a Antique Software downloads section. I don't know what you mean by 0.7 as that does not appear to be a valid version, did you mean 7.0? Anyhow if its not at t... |
1,004,676 | 1,004,684 | How to terminate a hanging thread inside a dll correctly? | Hi Everybody,
I have a third party library that contains an error. When I call a function it may hang. The library function is called inside a dll. I decided to move the call into the thread and wait for some time. If thread is finished then OK. If not – I should terminate it compulsory.
The simplified example here:
un... | Unfortunately, you can't arbitrarily terminate a thread safely.
TerminateThread causes the thread to terminate immediately, even if the thread is holding locks or modifying some internal state. TerminateThread can cause random hangs in your application (if the thread was holding a lock) or a crash (if the thread were ... |
1,004,701 | 1,005,591 | Model - View - Controller in Qt | I understand more or less how does MPV works.
But I don't get what classes:
QAbstractItemModel
QAbstractItemView
QAbstractItemDelegate / QItemDelegate
Can do for me?
If that is relevant, I'm using
QGraphicsScene / QGraphicsView with some elements (visual representation of game board) that user can interact with while... | AbstractItemModel QAbstractItemView QAbstractItemDelegate
Are from the "Mode/View framework"
This is a very powerful framework for the data part of your application, here is a presentation of the framework.
QAbstractItemModel
Is the base class for the model of the MVC. Has a global interface for accessing and altering... |
1,004,807 | 1,004,820 | Relationship between MSVC++ rand() and C# System.Random | How can I make it so the same sequence of random numbers come out of an MSVC++ program and a C# .NET program?
Is it possible? Is there any relationship between MSVC++ rand() and System.Random?
Given the example below it seems they are totally different.
#include <iostream>
using namespace std;
int main()
{
srand( 1... | It is possible (not exactlly easy) to use .NET mangaged libraries in unmanaged C++. You might want to take a look at the MSDN documentation.
|
1,004,961 | 1,004,975 | Bug on a custom C++ class | I need help on finding the problem using a custom c++ class to manage 3D positions. Here is the relevant code from the class
Punto operator+(Punto p){
return Punto(this->x + p.x, this->y + p.y, this->z + p.z);
}
Punto operator+(Punto *p){
return Punto(this->x + p->x, this->y + p->y, this->z + p->z);
}
... | The first one compiles fine because you can subtract pointers in C/C++, but not add pointers. But in any case it doesn't do what you need - it doesn't use your overloaded operator. Since your operators are defined in a class, you need to operate on class instances, not on pointers. So, change to something like
Punto p... |
1,005,072 | 1,005,772 | Exceptions on Linux from a shared object (.so) | I have a test program called ftest. It loads .so files that contain tests and runs the tests that it finds in there. One of these tests loads and runs a .so that contains a Postgres database driver for our O/RM.
When the Postgres driver throws an exception which is defined in that .so file (or one that it links to, but... | Assuming your using gcc -
Append -Wl,-E when you build the executable calling dlload(). This exports all type info symbols from the executable, which should allow the RTTI (when catching the exception) to work properly.
VC++ uses string compares to match typeinfo, results in slower dynamic_cast<> etc but smaller binari... |
1,005,318 | 1,005,372 | Migrating Borland C++ to C# | I have to execute project where I need to migrate Borland C++ code to C#,
what are the important steps I need to follow for smooth migration of code?
and please suggest any kind of Tips and Tricks?
| That actually means a complete re-write. If I were you, I'd try C++/CLI instead of C#. This way, you can acutally gradually rewrite your code and transform it to managed code.
Things to consider, wether you migrate to C# or C++/CLI:
Partition your software in modules with clean interfaces (using n-tier architectures, ... |
1,005,476 | 1,007,175 | How to detect whether there is a specific member variable in class? | For creating algorithm template function I need to know whether x or X (and y or Y) in class that is template argument. It may by useful when using my function for MFC CPoint class or GDI+ PointF class or some others. All of them use different x in them. My solution could be reduces to the following code:
template<int... | Another way is this one, which relies on SFINAE for expressions too. If the name lookup results in ambiguity, the compiler will reject the template
template<typename T> struct HasX {
struct Fallback { int x; }; // introduce member name "x"
struct Derived : T, Fallback { };
template<typename C, C> struct C... |
1,005,685 | 1,005,709 | C++ static initialization order | When I use static variables in C++, I often end up wanting to initialize one variable passing another to its constructor. In other words, I want to create static instances that depend on each other.
Within a single .cpp or .h file this is not a problem: the instances will be created in the order they are declared. How... | You have answered your own question. Static initialization order is undefined, and the most elegant way around it (while still doing static initialization i.e. not refactoring it away completely) is to wrap the initialization in a function.
Read the C++ FAQ items starting from https://isocpp.org/wiki/faq/ctors#static-i... |
1,005,780 | 1,005,859 | Scoping rules when inheriting - C++ | I was reading the C++0x FAQ by Stroustrup and got stuck with this code. Consider the following code
struct A
{
void f(double)
{
std::cout << "in double" << std::endl;
}
};
struct B : A
{
void f(int)
{
std::cout << "in int" << std::endl;
}
};
int main()
{
A a; a.f(10.10); ... | The first code works as c++ is designed to work.
Overloading resolution follows a very complicated set of rules. From Stroustrup's c++ bible 15.2.2 "[A]mbiguities between functions from different base classes are not resolved based on argument types."
He goes on to explain the use of "using" as you have described.
Th... |
1,006,147 | 1,007,484 | How do I detect desktop transition effects? | I want to minimise my application, take a screenshot of the current desktop and return my application back to its original state.
This has been working fine under windows XP, however under testing on different Vista machines the minimise time of 200 milliseconds is no longer valid.
Is there a way to ask the operating s... | The closest I can find is SPI_GETUIEFFECTS, which tells you if such effects are enabled at all.
If enabled, you could of course use SPI_SETUIEFFECTS to turn them off. But that's a rather shotgun method - how would you restore them? It's probably better to temporarily turn off the ones that bother you most.
|
1,006,172 | 1,006,206 | Pointer arithmetic on string type arrays, how does C++ handle this? | I am learning about pointers and one concept is troubling me.
I understand that if you have a pointer (e.g.'pointer1') of type INT that points to an array then you can fill that array with INTS. If you want to address a member of the array you can use the pointer and you can do pointer1 ++; to step through the array. T... | Quite simple.
An array of strings is different from a vector of strings.
An array of strings (C-style pointers) is an array of pointers to an array of characters, "char**". So each element in the array-of-strings is of size "Pointer-to-char-array", so it can step through the elements in the stringarray without a proble... |
1,006,214 | 1,006,238 | Why the below piece of code is not crashing , though i have deleted the object? | class object
{
public:
void check()
{
std::cout<<"I am doing ok..."<<std::endl;
}
};
int main()
{
object *p = new object;
p->check();
delete p;
p->check();
delete p;
p->check();
}
EDIT:
Gurus, i am confused by many of the statements "it may crash or may not".. why isnt there a standard... | Because what it actually looks like after the compiler has had its way, is something like this:
object::check( object* this )
{
// do stuff without using this
}
int main()
{
object *p = new object;
object::check( p );
delete p;
object::check( p );
delete p;
object::check( p )... |
1,006,364 | 1,006,399 | minimal cross-platform gui lib? | I'm looking for a minimal and easy to learn C or C++ cross platform gui library.
In a nutshell I only need the following functionality:
application window
menu bar
some simple dialogs, File-open and save. Maybe a user-written one.
user canvas where I can draw lines an circles on.
some kind of message/event loop mecha... | If you need something small, try FLTK libs: I used them at work (embedded development) and I think it's a valid option. Maybe apps are not as "cool" as QT-based ones, but developing with FLTK libs is fast and easy.
|
1,006,543 | 1,006,566 | A lightweight XML parser efficient for large files? | I need to parse potentially huge XML files, so I guess this rules out DOM parsers.
Is out there any good lightweight SAX parser for C++, comparable with TinyXML on footprint?
The structure of XML is very simple, no advanced things like namespaces and DTDs are needed. Just elements, attributes and cdata.
I know about Xe... | If you are using C, then you can use LibXML from the Gnome project. You can choose from DOM and SAX interfaces to your document, plus lots of additional features that have been developed over years. If you really want C++, then you can use libxml++, which is a C++ OO wrapper around LibXML.
The library has been proven... |
1,006,767 | 1,006,826 | Fast method to read and store serialized objects with pointers and pointers to pointers in C++ | I'm needing a fast method to read and store objects with pointers and pointers to pointers in xml files in c++ . Every object has it's own id , name , and class type.
| You should build a map of pointers to IDs as you serialise your data.
|
1,007,054 | 1,012,391 | Why can't I befriend a template parameter? | When researching an answer to a question (based on this answer) I tried to do the following:
template <class T>
class friendly {
friend class T;
};
friendly<string> howdy;
This fails to compile with the following error:
error: template parameter "T" may not be used in an
elaborated type specifier
... | A bit more googleling brought up Extended friend Declarations (PDF) for C++0x.
This document contains the following:
template <typename T> class R {
friend T;
};
R<C> rc; // class C is a friend of R<C>
R<int> ri; // OK: “friend int;” is ignored
Which goes even further than what I thought (ignoring illegal friend ... |
1,007,348 | 1,008,555 | Ms Sitelock 1.15 and VS 2005 | I'm trying to implement the MS Sitelock template into one of my Active-X Controls. I've downloaded the sitelock 1.15 sdk and I'm stuck on the very first step.
Including the sitelock.h header file causes a bunch of compile errors that have to do with the sal.h header file. It looks to me like sitelock.h wants to use ... | New SAL.H is included in the Windows server 2008 SDK, not the Vista one.
I'm still using the Vista SDK and have gotten by my compiler errors by translating the attribute sal macros to declspec sal macros in sitelock.h.
Used the notes in the following url to do the translation:
http://blogs.msdn.com/sdl/archive/2009/0... |
1,007,390 | 1,008,183 | Is it possible to make pointers to distinct template types convertible? | I have a template class that will bundle some information with a type:
template <typename T>
class X
{
int data[10]; // doesn't matter what's here really
T t;
public:
// also not terribly relevant
};
Then lets say we have a Base class and Derived class:
class Base {};
class Derived : public Base {};
I'd like t... | Rephrasing the question to a more general: is it possible to convert pointers from unrelated types if the unrelated types are themselves convertible?, the answer is not. And different template instantiations define different unrelated types.
You can implicitly convert (see note below) a pointer to a derived object to a... |
1,007,571 | 1,008,054 | Getting svn diff to show C++ function during commit | Whenever I do a commit cycle in svn, I examine the diff when writing my comments. I thought it would be really nice to show the actual function that I made the modifications in when showing the diff.
I checked out this page, which mentioned that the -p option will show the C function that the change is in. When I t... | Is there a simple regex to match a C++ function? No.
Is there a (complex) regex to match a C++. Maybe or could be possible to write one.
But I would say regular expressions neither are easily up to such a task (given you want some kind of excat match) nor are they the right tool for such a task.
Just think about case l... |
1,007,585 | 1,007,903 | Getting Loki Singleton to work in DLLs in VS 2008 C++ | I'm pretty sure this problem isn't new, and pretty sure it's hard to solve. Hopefully I'm wrong about the latter.
I'm trying to use the Loki::Singleton from Modern C++ Design in a program of mine.
However, I can't seem to get it to work across DLLs. I think I know why this is happening: the templated code gets insta... | I see in the Loki source directory that they have a specific SingletonDLL directory under test, looks like they use an exported, explicitly instantiated template (which would work). Hopefully that contains the code you want.
|
1,007,597 | 1,007,669 | STL vector allocations | I was wondering why the vector templates perform two allocations, when only one seems to be
necessary.
For example this:
#include <vector>
#include <iostream>
class A {
public:
A(const A &a) {
std::cout << "Calling copy constructor " << this << " " << &a << "\n";
}
A() {
... | It isn't performing two allocations, it is creating an object by the default constructor to pass into resize, then copying that object into the new position, then destructing the argument.
If you look at the arguments to resize:
void resize(n, t = T())
It has as a defaulted argument a default constructed object of typ... |
1,007,938 | 1,007,991 | Qt - creating QPainter | I'm trying to rewrite method paintEvent in my programm and change it.
void MainWindow::paintEvent(QPaintEvent *event)
{
QRegion reg = this->bgPixmapHandle->rect();
QPainter painter(this);
painter.setClipRegion(reg);
painter.drawImage(bgPixmapHandle->rect(), bgPixmapHandle);
painter.end();
}
Here I... | Include QPainter header file. QPainter class is only forward declared in one of the Qt headers you're including in that translation unit.
|
1,008,019 | 1,008,289 | C++ Singleton design pattern | Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Sing... | In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
Can any one provide me a sample of Singleton in c++?
Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed,... |
1,008,119 | 1,008,170 | Boost library setup for Codeblocks | How to use boost libraries with Codeblocks(Windows) ? What i need to do after downloading the library from boost site ? Any idea, suggestions, pointers ?
| Here are the instructions for setting up Boost with Code::Blocks
|
1,008,272 | 1,008,300 | How to avoid explicitly calling a constructor when passing temporary object by reference in C++? | Let's say I have a class:
class String
{
public:
String(char *str);
};
And two functions:
void DoSomethingByVal(String Str);
void DoSomethingByRef(String &Str);
If I call DoSomethingByVal like this:
DoSomethingByVal("My string");
the compiler figures out that it should create a temporary String object and call ... | You need to pass by const reference:
For:
void DoSomethingByVal(String Str);
In this situation the compiler first creates a temporary variable. Then the temporary variable is copy constructed into the parameter.
For:
void DoSomethingByRef(String const& Str);
In this situation the compiler creates a temporary variable... |
1,008,326 | 1,009,053 | COM event with binary data in arguments | I am trying to develop a COM object using C++ and ATL to be used by both C++ and C# Windows Mobile clients. The COM object wraps up all of the logic to connect to our server and send/receive data using our proprietary protocol. I am having some difficulty coming up with an OnReceive event that works correctly with C#... | You basically have two options: use a SAFEARRAY of BYTEs or stuff the data into a BSTR. The latter, although ugly, used to be the default hack to pass binary data to VB6 components. Although I have never tried it, I guess it should work for .Net, too.
|
1,008,343 | 1,008,439 | Boost.Python and Python exceptions | How can I make boost.python code python exceptions aware?
For example,
int test_for(){
for(;;){
}
return 0;
}
doesn't interrupt on Ctrl-C, if I export it to python. I think other exceptions
won't work this way to.
This is a toy example. My real problem is that I have a C function that may take hours to compute... | In your C or C++ code, install a signal handler for SIGINT that sets a global flag and have your long-running function check that flag periodically and return early when the flag is set. Alternatively, instead of an early return, you can raise a Python exception using the Python C API: see PyErr_SetInterrupt here.
|
1,008,449 | 1,008,470 | What does this mean? | This:
typedef HRESULT (*PFN_HANDLE)(ClassName&);
It's used like this:
DWORD ClassName::Wait(PFN_HANDLE pfnh_foo)
{
while (!done) {
waitCode = WaitForMultipleObjects(paramA, paramB, paramC, paramD)
if (waitCode == WAIT_OBJECT_0)
{
pfnh_foo(*this);
}
else
done;
}
return waitCode;
}... | Your wait() function basically waits for multiple objects and then invoke function using function pointer PFN_HANDLE if the wait is successful ( indicated by return value WAIT_OBJECT_0).
pfnh_foo(*this);
This calls the function pointed by pfnh_foo with argument *this.
Lets say we have function:
HRESULT someFunction(... |
1,008,514 | 1,188,838 | On closing a Qt 4.5 application, Visual Studio reports that it has detected memory leaks | I am building a Qt 4.5 application on Windows using Visual Studio 2008. Whenever I run my application in Debug mode and then close it, Visual Studio prints the following to the output pane:
Detected memory leaks!
Dumping objects ->
{696512} normal block at 0x01981AB0, 24 bytes long.
Data: < > 00 C... | I had a chance to profile my project using DevPartner. The surprising thing is that it reports memory leaks in QtGuid4.dll and QtCored4.dll; however, after manually looking at each case, I discovered that they were all false positives.
As a side note, there were no memory leaks reported in the code using Qt.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.