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 |
|---|---|---|---|---|
4,178,592 | 4,178,641 | Using C++ templates to create a class with custom components | Let me explain what I am asking for by an example. Imagine I have a class for a car.
Now, the car may have a lot of extras:
4 doors instead of only 2
Automatic door locking
4 Wheel drive
I want to create the class with any combination of these options. Any of these options needs some data members. Imagine the class n... | You want to use policy classes:
class FourDoorPolicy { Door m_doors[4]; ... };
class TwoDoorPolicy { Door m_doors[2]; ... };
class AutoDoorLockingPolicy { ... };
class ManualDoorLockingPolicy { void lockDoors(); ... };
class FourWheelDrivePolicy { TransmissionShafts m_shafts[4]; ... };
class TwoWheelDrivePolicy { Tra... |
4,178,655 | 4,179,723 | Migrating SDL_PeepEvents From SDL 1.2.14 to SDL 1.3 | I'm porting an OS X application written in C++ with the SDL 1.2 framework to iOS using the SDL 1.3 framework. There have been some changes to the methods, and I am having trouble rewriting a couple of pieces of code. Here are the comments and declarations for the SDL_PeepEvents method from 1.2.14:
/**
* Checks the e... | SDL 1.3, as you have stated uses event range instead of event mask. This code should work with SDL 1.3:
SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, SDL_USEREVENT, SDL_NUMEVENTS - 1); // Peek events in the user range
Another cosmetic thing - you do not have to check with an if for boolean variables and then return true/f... |
4,178,695 | 4,178,714 | C++ What is the purpose of casting to void? |
Possible Duplicate:
casting unused return values to void
I read some source code, and in it many virtual functions in the interface classes are declared and default-implemented as such:
virtual bool FunctionName(TypeName* pointer)
{
(void)pointer;
return true;
}
May I ask what is the purpose of casting the po... | Multiple purposes depending on what you cast
Marking your intention to the compiler that an expression that is entirely a no-op is intended as written (for inhibiting warnings, for example)
Marking your intention to to the compiler and programmer that the result of something is ignored (the result of a function call, ... |
4,178,829 | 4,179,021 | adding widget dynamically in qt | I have a small problem with adding widget to QMainWindow.
When i do it like that:
wsk_mainStatki = new mainStatki(this);
wsk_mainStatki ->setGeometry(0,0,400,300);
this->layout()->addWidget(wsk_mainStatki);
it's ok but i get warning:
QMainWindowLayout::addItem: Please use the public QMainWindow API instead
this is ... | I believe it means you are not expected to manually insert stuff into the layout of a QMainWindow, but instead use methods like addToolBar, setStatusBar or setCentralWidget. The layouting of your own widgets would happen in the centralWidget.
By the way, your mainStatki constructor is missing a call to the QWidget cons... |
4,178,889 | 4,178,919 | Is this there a defined behavior for this code that deletes a derived class through a base class pointer? | Does this code result in defined behavior?
class A {
int x;
};
class B {
short y;
};
class C {
double z;
};
class D : public A, public B, public C {
float bouncy;
};
void deleteB(B *b) {
delete b;
}
void is_it_defined() {
D *d = new D;
deleteB(d);
B *b = new D; // Is this any differ... | Quoting Herb Sutter :
If deletion can be performed
polymorphically through the base class
interface, then it must behave
virtually and must be virtual. Indeed,
the language requires it - if you
delete polymorphically without a
virtual destructor, you summon the
dreaded specter of "undefined
behavior".
... |
4,178,909 | 4,178,986 | Checking For Valid Input | I am currently working on a c++ program and I want to check to see if the input the user is making is valid. Currently my code works if the user inputs the proper input or if the user inputs a small incorrect number my pogram will tell the user that the input is invalid. Now my problem is that when the user inputs mult... | If the user types in something that can't be read into Input (it's not clear from your code what type Input is), that input will get stuck in the input stream and each iteration of the loop will keep failing to read in the input until you clear the stream.
You need to clear the stream flags and get rid of whatever bad ... |
4,178,910 | 4,178,978 | Compiled C++ executables HUGE? | After programming for a while in C, I decided to finally start to learn C++. This is sort of bothering me, as the standard 'hello world' in C is usually ~16KB, including all of the crud your compiler throws on there. (Using stdio)
However, when I create a C++ executable doing hello world, the file is ~470KB! I went ahe... | In a word, symbols.
The C++ standard library introduces a lot of symbols to your program, since most of the library exists primarily in the header files.
Recompile your program in release mode and without debug symbols, and you can easily expect the program to be significantly smaller. (Smaller still if you strip symbo... |
4,178,938 | 4,178,963 | Finding current mouse position in QT | This is my first attempt at writing a QT app, and I'm just trying to get a feel for how it works. My goal is to have a 400x400 widget which knows the exact position of the mouse when the mouse is hovering over it. For example, if the mouse was hovering in the top left corner, the position might be 10,10 (or something s... | For your widget, you must enable mouse tracking.
Then, you can either install an event filter, paying attention to mouse events and looking for the move event, or you can inherit from QWidget and override the mouse event, looking for mouse move events.
http://doc.qt.io/qt-4.8/qwidget.html#mouseTracking-prop
http://doc.... |
4,179,260 | 4,179,280 | Returning the class pointer through function | How can i return the pointer of the Foo class using its functions. The reason why i ask is because i want to make this code work
Class fo
fo.MakeA(34.5777).MakeY(73.8843);
Thank you very much in advance
| Assuming that you need a reference return type;
class foo {
public:
foo& MakeA(float a) {
// MakeA code logic here...
return *this;
}
foo& MakeB(float b) {
// MakeA code logic here...
return *this;
}
}
Otherwise, you can just return a copy (foo instead of foo&).
|
4,179,322 | 4,179,339 | How to convert boost path type to string? | Hello I currently have a program that gets a full path of a file's location and is put into a variable that is the type of: boost::filesystem2::path
I have looked up how to do this and have found that using:
string result1 = boost::filesystem::basename (myPath)
will convert the path to string BUT it only converts the... | You just need to call myPath.string().
|
4,179,345 | 4,179,416 | GCC -Wuninitialized not warning about uninitialized structs | #include <ctime>
#include <iostream>
#include <cstring>
int main()
{
struct tm tm ;
//memset(&tm, 0, sizeof(struct tm));
strptime("1 Jan 2000 13:00:00", "%d %b %Y %H:%M:%S", &tm);
time_t t =mktime(&tm);
std::cout << ctime(&t);
return 0;
}
g++ -Wuninitialized -O2 test.cpp doesn't warn about tm not having been initiali... | GCC can't look into the already compiled code of the strptime, mktime and ctime functions at compile time. You just pass the address of the struct, from the point of the call, without reading anything. Valgrind on the other hand executes your program and tracks all the memory and will check up whether there is a read b... |
4,179,349 | 4,179,571 | In C++, what is the proper way to insert a line at the beginning of a text file? | I am creating a large text file, the first line is a summary which depends on the contents. I am currently inserting a summary line that contains what I expect the summary to be, and after creating the file I compare this with what was actually written. If the information is different I overwrite the initial summary.
C... | As Ignacio says, most filesystems don't support insertion in files, not to mention text files. And the C++ standard library's notion of a file is a simple stream of bytes. And so a fixed size summary at the start, as it seems you were intending with your code, is one practical solution (note: your code doesn't appear t... |
4,179,549 | 4,179,560 | Tracking mouse cursor in QWidget | I am using the mouseMoveEvent to track the position of the mouse cursor in a simple QT app. My problem is that I want the mouseMoveEvent to fire only when the cursor is in a 400x400 QWidget. Right now it is firing no matter where the mouse is. Here is my code...
void IPA2::mouseMoveEvent(QMouseEvent * event) {
cou... | If I understand you correctly, you may just perform a check here like if (x,y in range) do_something.
Another way would be to create a fake widget with 400x400 dimensions and reimplement it's mouse event.
The third (probably an overkill) is to use event filters (see here).
Update:
You can't just "easily" handle the mou... |
4,179,647 | 4,181,574 | How to mark something in Qt as obsolete(deprecated)? | Is there Q_OBSOLETE or Q_DEPRECATED in C++ with Qt 4.7?
Or is there a similar C++ macro or keyword?
| By "deprecated constructs", you really mean "deprecated member functions". You're asking for a compile-time warning to draw your attention to the call site of any deprecated function.
This isn't possible in any reasonable way in standard C++, and I don't see any attributes in G++ that would support this either. Qt can'... |
4,179,655 | 4,179,719 | Getting input directly into a vector in C++ | Consider the following code piece:
...
int N,var;
vector<int> nums;
cin >> N;
while (N--)
{
cin >> var;
nums.push_back(var);
}
...
Is it possible to do this without using an auxillary variable, in this case var?
| Assuming you have already read the initial N, there is a nice trick using istream_iterator:
std::vector<int> nums;
nums.reserve(N);
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(nums));
The back_inserter object turns itself into an iterator that a... |
4,179,656 | 4,179,743 | OpenCV: Do we need to delete CvPoint's and how to do it? | So we have something like:
//...
for(i=0;i<out->size;i++)
{
CvPoint pt1 = { out->values[ i * out->dim + 0 ], out->values[ i * out->dim + 1]};
CvPoint pt2 = { out->values[ i * out->dim + 2 ], out->values[ i * out->dim + 3 ] };
cvLine(destination, pt1, pt2, CV_RGB(240, 255, 255), 1, CV_AA,... | You do not need to delete them, the compiler deletes the CvPoint instances automatically for you as they are stored on the stack.
|
4,179,695 | 4,179,778 | How can i initialize superclass params from within the child c-tor in C++? | Watch the following example:
class A {
public:
A(int param1, int param2, int param3) {
// ...
}
};
class B : public A {
public:
B() : m_param1(1), m_param(2), m_param(3), A(m_param1, m_param2, m_param3) {
// ...
}
};
B b;
Obviously, when "b" will be created, A's ctor will be called be... | "The parameters are not primitives". So you have something like this?
class Param { /*...*/ };
class A {
public:
A(const Param& param1, const Param& param2, const Param& param3);
};
class B : public A {
public:
B();
private:
Param m_param1;
Param m_param2;
Param m_param3;
};
And you want to pass the members... |
4,179,800 | 4,179,820 | The equivalent of ./configure in Windows? | What is the equivalent of ./configure in Windows?
Sometimes I download a C/C++ library and when I use the make it, it says "use ./configure" but obviously ./configure can only be used on a Linux machine and the libraries don't usually have instructions for compiling on Windows (although they do support Windows, they do... | Actually, ./configure is not Linux-specific at all. Its original purpose was to smooth over the differences between the many variants of Unix now thankfully relegated to the dust heap of history, but nowadays it may well know how to set up things to work on Windows.
I would install the MinGW/MSYS development tools and... |
4,179,869 | 4,179,874 | Minus of a variable in C++? | I have this equation:
R= 2*(-I dot N)*N + I
Can I simply type (-I) or something similar, or do I have to multiply I by -1?
| C++ has a unary minus operator that performs negation.
- x
This negates x, just like 0 - x or -1 * x would negate x. Note that the - in -1 * x is also the unary minus operator.
|
4,180,008 | 4,180,053 | Hints for the compiler to help it with the optimization task | The const and volatile chapter on the 'Surviving the Release Version' Article gave me the idea that the compiler can use the const keyword as hint for its optimization job.
Do you know some other optimization-hints for the compiler or design principles for functions so that the compiler can make them inline?
By the way... | It is rare that const qualification can help the compiler to optimize your code. You can read more about why this is the case in Herb Sutter's "Constant Optimization?"
Concerning your last question: in general, you should prefer to pass by value things that are cheap to copy (like fundamental type objects--ints and f... |
4,180,064 | 4,180,077 | How do I prevent deletion of a pointer without using const? | I have a class that contains a vector of object pointers. I have a GetObject(..) function in that class that looks through the vector, finds the object desired, and returns a pointer to it. However, if the user of the class does a delete() on that returned pointer, my program will crash because the vector still has a p... | The best way to solve this problem is to use a shared-ownership smart pointer like shared_ptr, which you can find in Boost, C++ TR1, and C++0x.
A smart pointer is a container that manages the lifetime of your dynamically allocated object for you. It takes responsibility for deleteing the object when you are done using... |
4,180,233 | 4,180,460 | C++ function converting question | I attempted to use boost::function<x> wrapper to store and convert my functional objects and I want to know if there a compile-check for "does a conversion from arbitrary type T to type boost::function<x> exists".
Here is a code example:
struct Functor {
int operator()(int) {
return 5;
}
};
// Should not f... | In addition to what @James wrote, it seems you rather want to have something like is_callable. These class templates handle functions/function pointers and function object classes or references to them for up to 5 parameters. Use them at your own risk :)
|
4,180,237 | 4,181,049 | executing filenames with spaces in cmd pmt Passed from c++ program | I am currently working on getting my program to execute a program (such as power point) and then beside it the path to the file I want to open. My program is getting the file's path by using:
dirIter2->path()
I get the 2 paths of the program and file, Merge them as one string and pass them into the following:
system(Pa... | In both C and C++, the '\' is an escape character. For certain things (like '\n' or '\t') it inserts a control code; otherwise, it just gives you the next character.
So if you do something like:
fopen("C:\users\bob\john is cool", "r");
it's going to try to open a file named
C:usersbobjohn is cool
If you want those '\... |
4,180,242 | 4,180,472 | Tips/Resources for Large Scale Cross-Platform Software Projects | I'm going to be starting a large scale software project involving a cross-platform GUI and heavy number crunching. I plan on writing most of the application back-end in C++ and CUDA, and the GUI in Qt4. I plan on using Make as my build system. This will be a project that will only have two developers, and will proba... | 1) The structure can be the same, but if you're including files in subdirectories, make sure you use '/ and not \. The former will also work on windows.
2) I'd check out cmake ( http://www.cmake.org/ ) for managing building across multiple platforms. This will take a lot of pain out of the process for you.
3) Use STL... |
4,180,394 | 4,182,144 | How do I create a simple Qt console application in C++? | I was trying to create a simple console application to try out Qt's XML parser. I started a project in VS2008 and got this template:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
return a.exec();
}
Since I don't need event processing, I was wondering whether I may get into trouble if I ne... | Here is one simple way you could structure an application if you want an event loop running.
// main.cpp
#include <QtCore>
class Task : public QObject
{
Q_OBJECT
public:
Task(QObject *parent = 0) : QObject(parent) {}
public slots:
void run()
{
// Do processing here
emit finished();
... |
4,180,413 | 4,184,307 | Access violation calling C++ dll | I created c++ dll (using mingw) from code I wrote on linux (gcc), but somehow have difficulties using it in VC++. The dll basically exposes just one class, I created pure virtual interface for it and also factory function which creates the object (the only export) which looks like this:
extern "C" __declspec(dllexport)... |
You're using one compiler (mingw) for the DLL, and another (VC++) for the calling code.
You're calling a 'C' function, but returning a pointer to a C++ Object.
That will never work, because VTable layouts are almost guranteed to be incompatible. And, the DLL and app are probably using different memory managers, so yo... |
4,180,437 | 4,180,469 | c++ IntelliSense: expression must be a modifiable lvalue | im getting these two errors
1>c:\users\owner\documents\visual studio 2010\projects\monopoly\monopoly\xfileentity.cpp(376): error C3490: 'pDrawMesh' cannot be modified because it is being accessed through a const object
IntelliSense: expression must be a modifiable lvalue
i declared pDrawMesh in my class than used it... | Your member function is const-qualified. You cannot modify any member variables from within a const-qualified member function unless they are declared mutable.
You need to make pDrawMesh mutable, remove the const-qualification from DrawMeshContainer, or find some other way to accomplish whatever it is you are trying... |
4,180,486 | 4,180,502 | C++ TR1: What is the proper way to use a uniform distribution to generate a random number in a const method? | I have a simple const method that wants to generate a random number
int Object::const_method() const {
std::tr1::uniform_int<int> uni(0,100);
// do some calculation
return result;
}
This results in your standard (if templafied) const violation error
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.5.1/../../../../i... | Make your mersenne_twister object mutable within your class. Without seeing all your code, (especially the do_something part), we can't be certain, but I'm guessing that you have an object within your class of type merseene_twister which you are using a function of which is not a const function itself. This is causin... |
4,180,605 | 4,180,660 | Fastest way to convert unsigned char 8 bits to actual numbers | I am using an unsigned char to store 8 flags. Each flag represents the corner of a cube. So 00000001 will be corner 1 01000100 will be corners 3 and 7 etc. My current solution is to & the result with 1,2,4,8,16,32,64 and 128, check whether the result is not zero and store the corner. That is, if (result & 1) corners.pu... | I would consider a different approach to it entirely: there are only 256 possibilities for different combinations of flags. Precalculate 256 vectors and index into them as needed.
std::vector<std::vector<int> > corners(256);
for (int i = 0; i < 256; ++i) {
std::vector<int>& v = corners[i];
if (i & 1) v.push_bac... |
4,180,616 | 4,181,320 | Reference counting in wxWidgets, how does it work in this simple case? | My program is crashing and I'm having a hard time wrapping my head around why it crashes. The main problem is that the wxwidgets documentation says that reference counting is used for wxImage objects. What exactly does this mean? Why does this code crash it?
wxImage* t = m_default_image; //m_default_image is a pointer ... | Let me explain what is happening:
You create a pointer to a wxImage that you have already created somewhere.
You then delete it.
You then attempt to dereference a deleted pointer and call 'IsOk()' on the resulting object, which doesn't exist anymore, because of the previous step.
Step 2 may or may not have actually d... |
4,180,626 | 4,180,646 | how to use extern keyword on struct | Please Help Me~ :)
Under code complie successful on visual studio. but, Under code could not complie on linux, g++.
The code..
A.h
struct Test { Test(); ~Test(); };
B.h
extern struct Test { Test(); ~Test(); };
A.cpp
#include "A.h"
Test::Test()
{
cout << "Construction" << endl;
}
Test::~Test()
{
cout << "... | Test is a data-type, so you don't need to use extern. As the error message says, extern is only for functions and objects. If Visual Studio is allowing your code to compile, then that's a "bug" in the compiler.
The point of extern is to tell the compiler not to worry about functions and objects that it cannot see, be... |
4,180,916 | 4,181,045 | ImageMagick "convert" utility Magick++ equivalent? | Sorry if the title didn't make any sense.
Currently, the following parameters on the imagemagick convert utility are perfect for what I need. I'm tring to take an .svg file, make it larger and write it as a png file.
convert -density 36 home.svg home_1.png
Unfortunately, I need to be using Magick++ (the C++ Interfa... | I'm no ImageMagick pro, but when I tried this code:
#include <Magick++.h>
int main(int argc, char **argv) {
Magick::Image img;
img.density(Magick::Geometry(36,36));
img.read(argv[1]);
img.write(argv[2]);
img.density(Magick::Geometry(72,72));
img.read(argv[1]);
img.write(argv[3]);
}
with this SVG file, ... |
4,180,943 | 4,181,033 | C++: getting a fact size of data in uchar/guchar? | The problem is simple: sizeof((u_char)value) returns 8. strlen fails. How to get a length of uchar's content?
Attempted
std::cout << "Data: " << (u_char *)data[0] << "\n"`;
u_char is defined in include/sys/*.h as unsigned char;
| sizeof() returns the number of bytes required to store the variable. So sizeof(u_char) == 8 means it takes eight bytes to store one u_char.
The reason you are getting a segmentation fault is because (u_char *)data[0] means you want the first element in the data array, then treat it as a memory address and dump the dat... |
4,181,001 | 4,181,040 | How to disable hints in Dev C++? | I have Bloodshed Dev C++ 4.9.9.2.
Every time I stop typing for a second this hint pops up and I can't see a thing what I'm typing! I have a feeling that it waits for a most unsuitable moment to pop up. Then it disappears in 2 secs, or, sometimes, whenever it wants.
Is there a way to disable it? (haven't found one in ... | I never used Dev-C++, but from searching on the Net I found two links:
http://www.bloodshed.net/dev/NEWS.txt
http://www.rohitab.com/discuss/topic/26479-dev-c-pauses-when-i-type-or-next-to-a-class/
In the first, it says that in version 4.9.5.5 they added an option for mouse hints disabling - maybe it will work for key... |
4,181,057 | 4,181,288 | Is the following C++ singleton implementation? | I did see on internet some pattern for implementing singleton class as following:
class singleton {
public:
int a;
void print()
{
std::cout << a << std::endl;
}
} singleton;
int main()
{
// singleton b; COMPILATION ERROR
singleton.a = 3;
singleton.print();
return 0;
}
It does ... | Regarding the two question that you literally ask,
yes, C++ has the notion of names of different kinds co-existing in the same scope, as in C, and
yes, when the appropriate header is included the code compiles fine with MinGW g++ 4.4.1, Visual C++ 10.0, and Comeau Online 4.3.10.1.
When you're in doubt about whether s... |
4,181,059 | 19,501,842 | Linkage of symbols within anonymous namespace within a regular namespace | In C++, putting a function or a variable in an anonymous namespace makes its linkage internal, i. e. the same as declaring it static on a file-level, but idiomatic C++.
What about an anonymous namespace within a normal namespace? Does it still guarantee internal linkage?
// foo.cpp
void func1() {
// external linka... | C++11 (draft N3337) §3.5/4: (emphasis mine)
An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. All other namespaces have external linkage. A name having namespace scope that has not been given internal linkage above has the same linkage as the enclosi... |
4,181,178 | 4,181,228 | Using precompiled headers with a static library project | I am in need of some advice on how to setup my project. I'm building a static library and want to know if the way I'm using precompiled headers is correct before I go too far.
So far, my stdafx file is just including (for types like DWORD, etc.) and (for std::string).
I built a simple cpp/header combo called TestFun... | Don't #include "stdafx.h" in your library's public header file. By public header file, I mean the header file that clients of your library would #include.
Instead, only define the absolute minimum, and preferably use 100% portable code in this file. Also avoid using the STL if your library is going to be used by diff... |
4,181,372 | 4,181,459 | Why doesn't Boost.Regex find multiple matches in one string? | I'm writing a small command-line program that asks the user for polynomials in the form ax^2+bx^1+cx^0. I'm going to parse the data later but for now I'm just trying to see if I can match the polynomial with the regular expression(\+|-|^)(\d*)x\^([0-9*]*)My problem is, it doesn't match multiple terms in the user-entere... | You're using the wrong thing -- regex_match is intended to check whether a (single) regex matches the entirety of a sequence of characters. As such, you need to either specify a regex that matches the whole input, or use something else. For your situation, it probably makes the most sense to just modify the regex as yo... |
4,181,403 | 4,181,628 | Generate Random Number Based on Beta Distribution using Boost | I am trying to use Boost to generate random numbers according to the beta distribution using C++. I have seen many examples online for generating random numbers according to distributions in random.hpp (e.g. this book). However, I cannot seen to translate them to use the beta distribution found in beta.hpp.
Thanks.
| You'll first want to draw a random number uniformly from the range (0,1). Given any distribution, you can then plug that number into the distribution's "quantile function," and the result is as if a random value was drawn from the distribution. From here:
A general method to generate random numbers from an arbitrary d... |
4,181,629 | 4,191,953 | Calling Boost from Ruby via SWIG? | Suppose I want to call one or more boost library functions from Ruby code. There are many examples of times where I'd want to do this, but most recently I want to use the Boost Graph library for efficient graph processing. I think the way most often suggested for doing this is to use SWIG. Has anyone gone through and g... | I can't say I have generated wrappers for the Boost libraries specifically, but I have done so for my own templated classes.
This is perfectly doable as long as you keep in mind that SWIG will wrap specific template instantiations using the %template directive.
As stated in the documentation linked above:
[...] a ba... |
4,181,630 | 4,181,643 | How Can I place a Line Break while writing to a file | I am creating a configuration file on click of a button by the following code.
fputs( "AutoStart = " +strAutoWinStart +
"AutLogHistory = " +strAutoLogSvrHistory +
"AutoScan= " +strAutoScanDetect +
"AutoMount = "+ strAutoMount +
"AutoOpen = "+ strAutoOpenWin +
"LastConnecte... | Add "\r\n" (or "\n" for UNIX-style linefeeds) to create a new line in the file.
Some editors on Windows such as Notepad don't handle UNIX-style linefeeds well, showing everything on one line. For the most portability across operating systems, use "\n". For the most usability in Windows, use "\r\n".
Even better: use std... |
4,181,639 | 4,181,681 | What have I done wrong with this simple template class? | I've written a little class to assist in conversions to and from MSVC's clunky types:
template <class FromType>
struct convert
{
convert(FromType const &from)
: from_(from) {}
operator LARGE_INTEGER() {
LARGE_INTEGER li;
li.QuadPart = from_;
return li;
}
private:
FromTy... | Class templates are never instantiated implicitly. Given the class definition you gave, you'd have to say:
convert<int>(0)
...to invoke that class's constructor.
With default template arguments, you could improve (?) it to:
template <class FromType = int>
struct convert
{ /* ... */ };
and then invoke it as:
convert<... |
4,181,737 | 4,181,782 | What's wrong with this c++ code? | I've made a few changes here but I'm still not getting what I expect to get. For example, when I substitute a for 1, b for 2 and c for 2, I should get -1+i and -1-i but when I run code it gives me -0.73205+i and - 2.73205+i. How do I fix this?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std... | At the first test for if (disc == 0.0 && b == 0.0), the variable disc is uninitialized and hence could have any value whatsoever. You probably intended to write if (a == 0.0 && b == 0.0)...
Your mathematics in the imaginary case is more than a little suspect. If the discriminant is negative, then you need the real p... |
4,181,835 | 4,183,216 | Get a file's size through `IShellItem` | I've implemented a directory walking algorithm for the Windows Shell using IShellItem, IShellFolder, IStorage, IStream, etc. All is well and good. I can even walk inside shell namespace extensions (e.g. .zip) files.
However, I have problems extracting (regular) file sizes when files are being used by some other program... | Have you tried getting hold of the IShellItem2 interface, and then querying for the value of the PKEY_Size property?
|
4,181,958 | 4,181,985 | Using operator overloading in C++ | class A
{
public:
ostream& operator<<(int string)
{
cout << "In Overloaded function1\n";
cout << string << endl;
}
};
main()
{
int temp1 = 5;
char str = 'c';
float p= 2.22;
A a;
(a<<temp1);
(a<<str);
(a<<p);
(a<<"value of p=" << 5);
}
I want the output to b... | There are 2 solutions.
First solution is to make it a template.
template <typename T>
ostream& operator<<(const T& input) const
{
cout << "In Overloaded function1\n";
return (cout << input << endl);
}
However, this will make the a... |
4,182,013 | 4,182,033 | What are the pros/cons of this class definition style? | I have seen following style class definition several times. What exactly are the pros/cons of this style?
typedef class _MyClass
{
public :
_MyClass();
} MyClass;
| It's pretty rare in C++, but common in C (where struct Foo does not automatically alias to just Foo.) You might see it in a library that has different classes for different platforms (e.g. a "Canvas" class, which is very implementation-specific.) The library would use the typedef to let its users simplify their code:
#... |
4,182,071 | 4,182,633 | write c++ function format_string for formatting like sprintf of std::string | For convenient usage I want to write formatting function similar to sprintf just returning std::string, like this:
std::string format_string(const char* format, ...)
I can use vsnprintf there but have problem - I don't know in advance how long temp buffer should be. On Microsoft have function _vscprintf that can do it... |
One option is have temp buffer start some known size then increase it if see it's not enough with vsnprintf. Are there better approach? Thanks
You can use vasprintf(), but that does an unnecessary heap allocation - it's unlikely to be faster on average. Using alloca you can avoid the heap. Or, you can write directl... |
4,182,277 | 4,182,319 | Boost shared_ptr with overloaded placement new/delete | I am using boost shared_ptr with my own memory manager like this (stripped down example, I hope there are no errors in it):
class MemoryManager
{
public:
/** Allocate some memory.*/
inline void* allocate(size_t nbytes)
{
return malloc(nbytes);
}
/** Remove memory agian.*/
inline void dea... | Because deleter should destroy the object:
class Deleter
{
public:
void operator()(Object *p) {
p->~Object();
globalMM.deallocate(p);
}
};
Edit: I was wrong in my deleter, fixed
|
4,182,610 | 4,182,665 | Ideal data structure with OpenMP | What is an ideal data structure in parallel programing, in my case OpenMP.
#pragma omp parallel for
for(int i = 0; i < N; i++)
{
if(table[i] == true)
container.insert(i); // ?? what kind
}
In this example it might be simple if we use a table of similar size. What is a more general data structure for shared... | It is best not to rely on shared data structures at all (because you'll have to rely on locks at some point, which will slow things down). Instead, have each thread write to its own structure, and coalesce the results once the parallel section has completed.
|
4,182,823 | 4,183,304 | Exception handling for Unit Tests in c++ | I'm trying to test a c++ code on an Nunit framework but I keep getting the following Exception
System.Runtime.InteropServices.SEHException : External Component has thrown an exception.
which is supposedly perfectly normal (I assume) anyway I wanna ignore it. (i.e. Use ExpectedException) This is my .h file
[Test, Desc... | Is the exception expected, or is the exception acceptable?
If it is expected, then your unit test framework should have some kind of API that allows you to state the expected exception, and to fail the test if it does not occur. A quick trawl through the documentation yields the incantation:
[ExpectedException( "Syste... |
4,182,863 | 4,182,908 | different outputs on different compiler |
Possible Duplicate:
FAQ : Undefined Behavior and Sequence Points
Different outputs on different compiler?
Is this true that certain statements can generate different outputs on different compilers. I have two compilers handy gcc and msvc expression edition. When I tried a code sample on both of them I was shocked to... | You invoke undefined behaviour by incrementing a more than once. Any compiler would be within their rights to break into your house and beat you with a stick.
|
4,182,866 | 4,183,040 | Why error LINK2005: object already defined error disappears when I declare the object as static | I have the follwoing structure and object of structure defined in the header file as below:
struct STConfigurationDetails
{
bool bAutoStart;
bool bAutoLog;
bool bAutoScan;
bool bAutoMount;
bool bAutoOpen;
bool bAutoDetectLast;
};
struct STConfigurationDetails g_objConfigurationDetails ;
In the... | Adding static might solve your linking problem, but gives you a much bigger problem. That variable is no longer global and has a different value in every CPP file that uses it. You need to declare it as extern in the header file and then declare it one more time in just one CPP file as is.
When you use static it means ... |
4,183,265 | 4,183,329 | How do I added an object to a vector<object> that's inside another class? | #include "player.h"
class team
{
public:
team();
void addPlayer(player);
void deletePlayer(int);
double getTotalCost();
int getPlayerCount();
double inBank();
string toString();
private:
player a;
int playerId;
double bank;
int i;
};
#include "../../std_lib_facilities.h"
#include "team.h"
team::team()
... | I assume this is what you meant:
#include "player.h"
#include <vector>
class team
{
public:
team();
void addPlayer(player);
void deletePlayer(int);
double getTotalCost();
int getPlayerCount();
double inBank();
string toString();
private:
vector<player> a;
int playerId;
double bank;
int i;
};
#include "..... |
4,183,462 | 4,183,475 | Is there a way to call std::transform with a function with multiple arguments | Hello I have a function which signature is
std::string f(double x, double param1, double param2, double param3);
I would like to call it on a std::vector xvalues for the parameter x using something like std::transform for a particular value of param1, param2 and param3.
It would be the equivalent of:
double param1(1.)... | You should look into boost::bind which will allow you, as the name indicates, to 'bind' arguments to your function f :
std::transform([...], boost::bind(&f, _1, param1, param2, param3));
The result of this bind is an unary function (_1 being a placeholder for the argument which it should be called with) : all other p... |
4,183,572 | 4,183,636 | How can I read a file line content using line number | I have the following code snippet which is working fine:
ifstream NDSConfig( "NDS.config" ) ;
string szConfigVal ;
while( getline( NDSConfig, szConfigVal ) )
{
//code
}
But the problem is I need to update a check box state by comparing the line values. The code then will si... | Alternatively, use boost::program_options, this is designed perfectly for what you require!
EDIT: little more detail, program_options has a method to parse a config file, such as yours, and as you configure program_options, you can pass in the variable to store the value from the config file in. Have a look at their si... |
4,183,847 | 4,184,029 | C++: how can I get the list of folders | I am not familiar with C++ as I am a C# developer.
In my project, I need to delete all folders of one week before. In C++, how can I get the list of the folders of one week before based on the current system date time?
I am working on Eclipse IDE running on Ubuntu 10.10.
If you could provide some sample of code, that ... | With boost:
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
int main(int, char**)
{
time_t one_week_ago = std::time(NULL) - (7 * 24 * 3600);
boost::filesystem::directory_iterator dir("/tmp"), end;
BOOST_FOREACH(const boost::filesystem::path& p, std::make_pair(dir, end))
if(boost::fil... |
4,184,105 | 4,184,133 | Regex and Boost. Not working on a simple regex | Below is my following code
#include <iostream>
#include <stdlib.h>
#include <boost/regex.hpp>
#include <string>
using namespace std;
using namespace boost;
int main() {
std::string s = "Hello my name is bob";
boost::regex re("name");
boost::cmatch matches;
try{
// if (boost::regex_match(s.be... | from boost regex:
Important
Note that the result is true only if the expression matches the whole of the input sequence. If you want to search for an expression somewhere within the sequence then use regex_search. If you want to match a prefix of the character string then use regex_search with the flag match_continuous... |
4,184,148 | 4,184,365 | Can my code use a 'T' or 'const T &' specialization, whichever is available? | We are working with an inhouse library which features a StringBuilder class which is used to turn a list of VariableValue objects into a string. VariableValue objects can be constructed from arbitrary types (by specializing a convertVariable template function). Here's the code which describes the scenario:
struct Varia... | I'm not quite sure my answer will be of any help, but it's worth trying. From your post, I tend to think that the appropriate solution is to change the signature of convertVariable. You say that this is expensive because there are a lot of specialization, but I think it could actually be free depending on the way you c... |
4,184,281 | 4,184,390 | how to resolve th "C4653" warning in vs2010? | I am converting c++ project from 2008 to 2010, with warning level 4
the "Warning C4653: compiler option 'Optimizations (one or more of /Oawp[y])' inconsistent with precompiled header; current command-line option ignored"
warning has been thrown.
| If there are no special .cpp files in the project that require special optimization options then all files should have the same options. Reset options that were set on specific files to projets defaults, and then change only the options you like for the whole project.
If you actually need some .cpp files to have specia... |
4,184,351 | 4,184,378 | Dealing with circular inclusion in a parent/child class relationship | Assume I've made a class, say Parent, that has a composition relation with Child. The parent class holds a list of children.
I want all children to hold a reference to the parent, so every child holds a Parent pointer.
This will cause circular inclusion. I refer to Child in parent.h and I refer to Parent in child.h. Th... | You'll have to use forward declaration:
//parent.h
class Child; //Forward declaration
class Parent
{
vector<Child*> m_children;
};
//child.h
class Parent; //Forward declaration
class Child
{
Parent* m_parent;
};
|
4,184,366 | 4,184,380 | How Can I execute my code on MessageBox Ok click | This might be very simple but I am new to MFC.
I have a messagebox:
MessageBox("Do You Want to Save the Configuration Changes","NDS",1);
which have Ok and Cancel option. I want to write my code on click of OK
| if(MessageBox("Blah", "NDS", 1) == IDOK)
{
// they hit okay
}
http://msdn.microsoft.com/en-us/library/ms645505(VS.85).aspx
|
4,184,468 | 4,184,493 | Sleep for milliseconds | I know the POSIX sleep(x) function makes the program sleep for x seconds. Is there a function to make the program sleep for x milliseconds in C++?
| Note that there is no standard C API for milliseconds, so (on Unix) you will have to settle for usleep, which accepts microseconds:
#include <unistd.h>
unsigned int microseconds;
...
usleep(microseconds);
|
4,184,595 | 4,194,257 | Nesting QMainWindows in Qt | I'm making a game in Qt.
The game itself is displayed by QGraphicsView/QDockWidget in a QMainWindow.
But now i'm trying to make a menu for it, so I thought to make an extra QMainWindow with QPushButtons. But I want this all to be integrated in one QMainWindow.
So when I click "New Game" in the menu, the game(QGraphicsV... | You could switch to QML (Qt Declarative) where it would be easy to use a state with menus shown and another one for displaying the game without menus.
|
4,184,601 | 4,185,864 | Do I put 'const' in my UML diagram? | I'm making a UML diagram using Dia. Do I need to put const in the diagram when a function is const? If so, where?
| Chapter 11.8.2 ("Operation") in the latest UML specification lists isQuery as one of the operation's attributes:
isQuery : Boolean - Specifies whether an execution of the Operation leaves the state of the system unchanged (isQuery=true) or whether side effects may occur (isQuery=false). The default value is false.
... |
4,184,789 | 4,185,301 | How to use libavcodec in Qt4? | How do I use libavcodec in Qt4 to access individual video frames?
After verifying that the video stream can be decoded by libavcodec by compiling this example, I moved the source code to my C++ program. Now av_open_input_file() is suddenly unable to open my video file (returning an errorcode: -2).
The call looks like t... | Well, this is embarrassing:
When I transfered the source code from the example to the c++ application I made a stupid mistake when I got linker errors, that told me that av_register_all(); was unavailable... and I renamed it to avcodec_register_all(), a little while later I fixed the linker problem and forgot about it.... |
4,184,917 | 4,184,983 | Help me understand this usage of boost::bind | Please have a look at this example posted by Johannes Schaub to sort a vector of pairs:
How do I sort a vector of pairs based on the second element of the pair?
std::sort(a.begin(), a.end(),
boost::bind(&std::pair<int, int>::second, _1) <
boost::bind(&std::pair<int, int>::second, _2));
I thought I... | boost::bind overloads the operator ! and the relational and logical operators ==, !=, <, <=, >, >=, &&, ||, so this is why you "see" a boolean expression, but you're really getting back a function predicate.
From there you can see that you're binding the second member of the pair for the 1st and 2nd arguments of the ov... |
4,184,973 | 4,185,263 | One question about function definition in C++ | I'm reading some material about function pointer in C++, and come across one function definition which I do not understand.
Standard function definition have the form:
type name (param...)
But the following definition seems a little strange to me. Can anyone explain it to me ?
Thanks.
float (*GetPtr1(const char opCode... | The rule for reading hairy declarations is to start with the leftmost identifier and work your way out, remembering that () and [] bind before * (i.e., *a[] is an array of pointers, (*a)[] is a pointer to an array, *f() is a function returning a pointer, and (*f)() is a pointer to a function):
GetPtr1 ... |
4,185,350 | 4,185,460 | Is it safe to push_back 'dynamically allocated object' to vector? | Whenever I need to add dynamically allocated object into a vector I've been doing that the following way:
class Foo { ... };
vector<Foo*> v;
v.push_back(new Foo);
// do stuff with Foo in v
// delete all Foo in v
It just worked and many others seem to do the same thing.
Today, I learned vector::push_back can throw ... | If all you care about is exception-safety of this operation:
v.reserve(v.size()+1); // reserve can throw, but that doesn't matter
v.push_back(new Foo); // new can throw, that doesn't matter either.
The issue of a vector having responsibility for freeing the objects pointed to by its contents is a separate thing, I'... |
4,185,388 | 4,185,496 | Qt - QProcess is not working | I try to launch internet explorer, So I use the below code
QProcess * process=new QProcess(this);
QString temp="C:\\Program Files\\Internet\ Explorer\\iexplore.exe";
process->startDetached(temp.toStdString().c_str());
But it doesn't work.
| Try:
QProcess * process=new QProcess(this);
QString temp="\"C:\\Program Files\\Internet Explorer\\iexplore.exe\"";
process->startDetached(temp);
You need to use escaped quotes since the path has a space in it, or possibly escape all the spaces (you missed Program\ Files in the code you posted).
|
4,185,499 | 4,185,576 | Does google protocol buffers support size calculation before serialization? | My (DSP) application produces data at a constant rate. The rate depends on the configuration that is selected by the user. I would like to know how many bytes are generated per second. The data structure contains a repeated (packed) floating point field. The length of the field is constant, but can be changed by the us... | It's impossible to know ahead of time, because protobuf packs the structures it is given into the fewest bytes possible - it won't use four bytes for int x = 1; for example - so the library would have to walk the entire graph to know the output size.
I believe you could find this out by doing a serialize operation to a... |
4,185,638 | 4,185,742 | Solving the Visual Studio 2010 AlwaysCreate rebuild issue | I've a C++ project that I'm currently porting from VS2008 to VS2010. When I build the project, Visual Studio 2010 reports the build as successful but if I then press F5 to start the debugger I'm told that the project is not up to date. If I ignore this warning, I can continue debugging ok, but if I press ok, the whol... | I've had this problem many times and it was always frustrating. I'll tell you what the problem was in my case, but first I have to ask you:
Did you do a rebuild-all before you tried running the first time, or just a rebuild?
Once you do a rebuild all, does it ask you yet again to rebuild if you've made no changes?
T... |
4,185,687 | 4,185,709 | Another BUG of VC++ 2010? About declaring a constant REFERENCE in a header | Several lines of code are worth a thousand words:
I have three simple files: header.h, main.cpp, other.cpp
// header.h
#pragma once
inline const int& GetConst()
{
static int n = 0;
return n;
}
const int& r = GetConst();
// main.cpp
#include "header.h"
int main()
{
return 0;
}
// other.cpp
#inc... | The paragraph you cite from the C++ Standard reads (C++03 7.1.1/6):
Objects declared const and not explicitly declared extern have internal linkage.
You have not declared an object. You have declared a reference. A reference is not an object. That said, 3.5/3 says:
A name having namespace scope has internal linka... |
4,185,776 | 4,185,827 | What does *& mean in a function parameter | If I have a function that takes int *&, what does it means? How can I pass just an int or a pointer int to that function?
function(int *& mynumber);
Whenever I try to pass a pointer to that function it says:
error: no matching function for call to 'function(int *)'
note: candidate is 'function(int *&)'
| It's a reference to a pointer to an int. This means the function in question can modify the pointer as well as the int itself.
You can just pass a pointer in, the one complication being that the pointer needs to be an l-value, not just an r-value, so for example
int myint;
function(&myint);
alone isn't sufficient and ... |
4,185,938 | 4,186,395 | Lightweight portable C++ threading | Does anyone know about a lightweight portable C++ threading library, that can work on Windows, Linux and Mac OS X?
Specifically in my case, I do a simulator that after each time passes exports simulated data. I would like to run only one thread (simulate) that would once in a while start another thread (export). The on... | What about TinyThread++?
Need portable threads for your C++
app? Is C++0x unavailable for your
target compiler(s)? Is Boost too
large?
Then you need TinyThread++!
TinyThread++ implements a fairly
compatible subset of the C++0x thread
management classes.
|
4,186,079 | 4,186,166 | find middle elements from an array | In C++ how can i find the middle 'n' elements of an array? For example if n=3, and the array is [0,1,5,7,7,8,10,14,20], the middle is [7,7,8].
p.s. in my context, n and the elements of array are odd numbers, so i can find the middle.
Thanks!
| This is quick, not tested but the basic idea...
const int n = 5;
// Get middle index
int arrLength = sizeof(myArray) / sizeof(int);
int middleIndex = (arrLength - 1) / 2;
// Get sides
int side = (n - 1) / 2;
int count = 0;
int myNewArray[n];
for(int i = middleIndex - side; i <= middleIndex + side; i++){
myNew... |
4,186,165 | 4,186,424 | Best Practise and Semantics of namespace nested functions and the use of extern "C" | I am creating a C++ library with a C-ABI interface.
This is how GCC treats the extern "C" qualifier with regards to mangling:
namespace x {
extern "C" int monkey(int x) {
return 1;
}
int chimpanzee(int x) {
return 1;
}
}
The relevant nm output:
00000000004005cd T _ZN1x10chimpanzeeEi
0... | This is for MSVC.
The namespace itself is not name-mangled, but the name of the namespace is incorporated in to the function's (or object's) name when name mangling occurs. This process is undocumented, but described here.
Answering your specific questions by jumping around:
1) There is no Standard-defined behavior re... |
4,186,503 | 4,186,644 | Understanding the working of logb() | I am trying to understand the working of logb() , It's manual says "The logb() function computes exponent of x, which is the integral part of $ \log_r^{|x|} $, as a signed floating point value, for a non-zero x, where r is the radix of the machine's floating-point arithmetic."
I am inquisitive to know to compute this ... | FLT_RADIX in <float.h>. In the real world it's always 2, and IEEE floating point requires it to be 2.
|
4,186,547 | 4,186,561 | C++: Write to an existing file? | In C++, I need to write to an existing file and keep the previous content there.
This is what I have done:
std::ofstream logging;
logging.open(FILENAME);
logging << "HELLO\n";
logging.close();
but then my previous text is overwritten (gone). What did I do wrong?
Thanks in advance.
| logging.open(FILENAME, std::ios_base::app);
|
4,186,643 | 4,186,699 | linux- windows cross c++ application | I'm developing an application which has to run on Linux and Windows.
I have an object called obj which I want to use in the code and it has different behavior on Linux and Windows. so I inherit aaa and called WindowsObj for Windows object and LinuxObj for Linux object.
My question is: How to use this object in the code... | The same thing :)
class _object
{
};
class WindowsObject : public _object
{
};
class LinuxObject public _object
{
};
#if defined(WIN32)
typedef WindowsObject Object;
#else
typedef LinuxObject Object;
#endif
Object myObject;
EDIT: Naturally, the interface that WindowsObject and LinuxObject expose must be the same.... |
4,186,651 | 4,186,714 | std::priority_queue: Custom ordering without defining comparator class | I want to have a priority queue with custom ordering, but lazy as I am, I don't want to define a comparator class implementing operator().
I really would like something like this to compile:
std::priority_queue<int, std::vector<int>,
boost::bind(some_function, _1, _2, obj1, obj2)> queue;
where some_function is a ... | This could work:
std::priority_queue<int, std::vector<int>,
boost::function<bool(int,int)> >
Then pass in your bind expression to the queue's constructor.
P.S. you're getting those compilation errors because you're putting runtime-evaluated expressions where a typename or constant expression are expected.
|
4,186,713 | 4,186,758 | Effective data structure for both deleteMin and search by key operations | I have 100 sets of A objects, each set corresponding to a query point Qi, 1 <= i <= 100.
class A {
int id;
int distance;
float x;
float y;
}
In each iteration of my algorithm, I select one query point Qi and extract from the corresponding set the object having the minimum distance value. Then, I have t... | std::map or boost::multi_index
|
4,186,903 | 4,187,114 | Cannot access PHP/C++ shared memory over the web | I am sharing some memory between C++ and PHP
At the PHP end I have:
$inputshm_id = shmop_open($shid, "w", 0777, 1024);
Where shid is an identifier I created with ftok.
This all works fine when I run this PHP script logged in as root on the server but when I try to run it remotely over the web I get:
Warning: shmop_... | The issue is that SELinux is blocking the shm access (you can verify by running setenforce 0, testing, and running setenforce 1 after), but I don't know a good way of solving it other than modifying the policy or switching to mmap.
|
4,186,913 | 4,187,045 | How to handle missing 'emplace_range' in C++0x STL? | I have two containers, let's say they're defined like this:
std::vector<std::unique_ptr<int>> a;
std::vector<std::unique_ptr<int>> b;
Assume both a and b are populated. I want to insert the entire container a to a particular location in b, using move-semantics so the unique_ptrs move to b. Let's assume i is a valid... | auto a_begin = std::make_move_iterator(a.begin());
auto a_end = std::make_move_iterator(a.end());
b.insert(i, a_begin, a_end);
|
4,187,044 | 4,238,017 | Stable Fluids in 3D Example | Has anyone run across or have an example of Jos Stam's Stable Fluids but in 3D? I need to pursue a 3D version of this in openGL but have been having a terrible time doing so. Is there an example of this preferably in openGL/C/C++?
| This is the best information I found about solving the Navier Stokes equitation (searched about 6 month ago): link text. It explains every part of the equitation solver in the most easy way that I have ever found. I haven't looked intensively into Jos Stam's paper, but it seems to be based on this equitation.
However ... |
4,187,184 | 4,187,303 | print time on each call to std::cout | How would someone do that?
for example I do like:
std::cout << "something";
then it should print the time before "something"
| You could use a simple function that prints the timestamp and then returns the stream for further printing:
std::ostream& tcout() {
// Todo: get a timestamp in the desired format
return std::cout << timestamp << ": ";
}
You would then call this function instead of using std::cout directly, whenever you want a time... |
4,187,229 | 4,187,263 | Is it possible to sandbox and run C++ or C# code that's entered in a textfield in a browser? | I'm diving into web development after ten years of desktop development and I'm experimenting with some testing concepts. I was wondering if it's possible to sandbox and run C++ code that's entered in a textfield in a browser? By that, I mean run the C++ or C# code on the backend webserver and return an analysis of th... | You might find the codepad about page interesting.
|
4,187,278 | 4,187,314 | Howto initialize a reference to an object if reference is a class member? | Let's say Class contains a reference called matrix_:
Class.h
class Class
{
Matrix& matrix_;
}
Class.cpp
Class::Class() : matrix_(Matrix())
{
}
I get the error: invalid initialization of non-const reference of type ‘Matrix&’ from a
temporary of type ‘Matrix’.
I see that the problem is that the temporary object w... | Class::Class() : matrix_(Matrix()) tries to set the reference to point to a temporary object, which is illegal.
well, there's a case with const references and temporary binding, but seriously, don't go there.
Looks like you just need to use aggregation:
class Class
{
const Matrix matrix_;
};
And the initializer list:
... |
4,187,416 | 4,187,582 | 'Field Scraping' in Windows | I want to develop an auditing application for certain Windows applications. I want to grab the text from MessageBoxes, Windows, Forms, Selections etc and ideally I would like to program in C++.
I've looked into Windows UI Automation as a possible solution, but am slightly put off as it says it will need to know parts ... | Look into using the accessibility layer, MSAA
|
4,187,746 | 4,250,985 | Const method accessing static variables | I apologize if this has been asked before. My search results did not turn up a similar question.
This is a conceptual question. According to MSDN and others as well:
A constant member function cannot modify any data members or call any member functions that aren't constant
Why then are we allowed to access static mem... | The C++ standard says this about const member functions:
If the member function is declared const, the type of this is const X*, [...]
In a const member function, the object for which the function is called is accessed through a const access path; therefore, a const member function shall not modify the object and its ... |
4,187,850 | 4,187,955 | packet fragmentation for raw sockets | If I am using raw sockets to send a UDP packet of size 3000bytes, do I need to handle packet fragmentation myself in the code, or should the raw socket handle fragmentation similar to DGRAM socket?
| Well, if you are using UDP, you aren't really sending RAW. RAW would be no IP at all, in which case yes you have to handle fragmentation yourself.
With UDP you get IP's fragmentation support, which is IMHO plenty good enough for short-haul networks where collisions should be minimal. Make the link between the two syste... |
4,187,967 | 4,188,217 | How to generate compile time errors? | I would like to be able to do something like this:
void f(int*p = nullptr)
{
if (!p)
{
//HERE I WOULD LIKE TO HAVE AN MSG THAT WOULD BE DISPLAYED DURING COMPILATION AS A WARNING POSSIBLY
}
}
| The correct answer is: What you're trying to do won't ever work.
|
4,188,273 | 4,188,289 | Language choices for writing very fast abstractions interfacing with Python? | I have a system currently written in Python that can be separated into backend and frontend layers. Python is too slow, so I want to rewrite the backend in a fast compiled language while keeping the frontend in Python, in a way that lets the backend functionality be called from Python. What are the best choices to do s... | C++ with SWIG can generate all of the glue code you need. So long as you avoid excessive jumps between C++ and python it'll be as fast as your C++. SWIG interfaces are usually fairly straightforward to generate unless you're doing something "odd".
|
4,188,306 | 4,188,344 | flicker free tab control with WS_EX_COMPOSITED | I have a VS2008 C++ application for Windows XP SP3 developed using WTL 8.1. My application contains a tab control that flickers when the application border is resized.
My window hierarchy looks like this:
CFrameWindowImpl CMainFrm
|-CSplitterWindow Splitter
|-CTabView Configuration Tabs
| |-CDialogImpl Co... | A window flickers because it gets erased before it's drawn. To eliminate this you need to disable erasing of the window entirely and use double buffering - draw the window contents into a bitmap, then copy the bitmap to the window. Because the bitmap contains the entire contents including the background, there's no nee... |
4,188,329 | 4,188,463 | Using Qt's QGraphicsScene/QGraphicsView for 2D games | Has any of you guys ever tried writing a 2d game in C++ using Qt's QGraphicsScene/QGraphicsView classes for the purpose of rendering and collision detection?
Do they perform well if there are many moving/animated objects on the scene? Are there any caveats? In general, can you point me to any games written using Qt's g... | I tried to use them for rendering. They don't perform very well, besides Qt itself is not very adapt for a game: they're a pretty heavy library doing lots of stuff. Their event handling is not lightweight.
If it's a simple game you should be ok; that API is really easy to use and can be set to use OpenGL or software re... |
4,188,572 | 4,188,604 | core dump segmentation fault with C++ | I am a newbie to the C/CPP application and analysing an issue with a piece of C/CPP code. I came across a Segmentation Fault error and I am not to identify the root cause of the segmentation fault.
Please find the scenario below:
union Value
{
int value_int;
float value_float;
RWCString *value_string;
}
voi... | You probably want to do something like:
value.value_string = new RWCString(value_string_arg);
In your code, if value.value_string is an uninitialised pointer, then the assignment you're doing will try to write to some random part of memory, causing the segmentation value. In my code above, the new operator allocates a... |
4,188,782 | 4,189,094 | Set DCB Fails When Attempting to Configure COM Port | I'm trying to write a C++ MFC application that uses the serial port (e.g. COM8). Every time I try to set the DCB it fails. If someone can point out what I'm doing wrong, I'd really appreciate it.
DCB dcb = {0};
dcb.DCBlength = sizeof(DCB);
port.Insert( 0, L"\\\\.\\" );
m_hComm = CreateFile(
port, ... | I was able to resolve the problem using BuildCommDCB:
DCB dcb = {0};
if ( !::BuildCommDCB( _T("baud=38400 parity=N data=8 stop=1"), &dcb ) )
{
TRACE(_T("CSerialPort : Failed to build the DCB structure - Error: %d"), GetLastError());
ThrowException();
}
|
4,189,156 | 4,189,187 | how to add template parameter to global function? | I'm working with some legacy code, and trying to get it to compile in Linux. It was originally built in visual studio, whose compiler didn't keep with standards. Anyways, now I'm going through the code fixing it and I came across a templated function that is declared globally. I get the error:
/home/blah/blah;/blah.h:... | Put a declaration of Clip somewhere before the template definition that caused this error. If Clip itself is not a template, an ordinary declaration will do. If Clip is a function template and you find the definition of Clip, you can usually just copy the start of that definition and replace the {...} with a ; to get... |
4,189,173 | 4,189,220 | Good precautions (practices) to start C++ programming |
I'm starting C++ programming in my first job. I'm a CS student and I have learn programming in Java. What advice would you tell me to watch out so I don't cause trouble in my new job?
Would you have any advice or references would be appreciated.
(example: I know C++ is more likely to have memory problem than Java)
Tha... | Maybe you already know this, but one common mistake for folks used to Java and learning C++:
Don't use new unless you have to (and you probably don't really have to). In most cases where you want to create an object, you should just create it "on the stack", like ClassType obj;.
|
4,189,468 | 4,189,516 | DLLImport: passing short type parameter | I'm trying to pass parameter of short type to C++ unmanaged function imported from DLL. In my C++ DLL code I have a following function:
__declspec(dllexport)void ChangeIcon(char *executableFile, char *iconFile,
UINT16 imageCount)
{
// Some code, doesn't matter
}
In C# managed code I import this function with t... | Make sure the calling convention matches. If you don't specify a calling convention StdCall is assumed. However for C/C++ the standard calling convention is Cdecl. So either use __stdcall on your C++ function:
void __declspec(dllexport) __stdcall ChangeIcon(char *executableFile, char *iconFile,
UINT16 imageCount)
... |
4,189,667 | 4,189,746 | Usage of virtual class and extern in C++ | I've been developing in C++ for some time when I was a student, but I never used virtual class or extern in C++ in any of the projects. I just recent read about these two, and was hoping if someone had a better understanding of their usage.
What is the purpose of virtual class? An example of where it could be used/impl... | Virtual classes are for when you encounter the dreaded diamond. For example:
struct Base { int x; };
struct D1 : Base {};
struct D2 : Base {};
struct Derived : D1, D2 {};
Here, Derived actually has two Base parts, and as a result two member variables called x. It will compile, but you might experience some unexpected ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.