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 |
|---|---|---|---|---|
1,711,525 | 1,712,115 | Why this program fails (sometimes)? | #include <cstdio>
#include <QtCore/QProcess>
int main (int argc, char** argv) {
// if we remove 3 following lines, the problem described below doesn't exists!!
QProcess process;
process.start ("asdqwe"); // doesn't matter what we try to execute here.
process.waitForStarted (1000);
while (true) {
char bu... | Your scanf was interrupted by SIGCHLD signal that was caught when child process terminated. In this case EOF is also returned.
QProcess stuff does set up signal handler for SIGCHLD (check sources): (4.5.3 here)
Q_GLOBAL_STATIC(QProcessManager, processManager)
QProcessManager::QProcessManager()
{
#if defined (QPROCESS... |
1,711,731 | 1,711,972 | Initialising classes inside another class in C++? | I have this definition in a header file:
class Owner
{
private:
// Fields
Child* _myChild1;
public:
// Constructors
Owner();
Owner(const char childName[]);
};
and this implementation:
Owner::Owner(const char childName[])
{
//do some operations - children must be created after these ops
_myChild = n... | Basically, how it works is thus:
If the Child class is fully defined before the Owner class, it can be included in the Owner in it's entirety, or as a pointer, whichever you prefer.
If the Child class is not fully defined before the Owner class, it would have to be forward declared and can only be included as a pointe... |
1,711,733 | 1,711,807 | Does anyone know where I can find the standard windows file dialog toolbar icons? | I'm trying to roll my own implementation of IShellBrowser because I need to have a more full-featured File Open and Save As dialog than Windows allows that is compatible with XP (and ideally with W2000)*
At this point I need to add the standard toolbar that you see in upper right of the dialog (manifest styles for XP a... | Try shell32.dll, in Windows\System32.
|
1,711,990 | 1,711,995 | What is this weird colon-member (" : ") syntax in the constructor? | Recently I've seen an example like the following:
#include <iostream>
class Foo {
public:
int bar;
Foo(int num): bar(num) {};
};
int main(void) {
std::cout << Foo(42).bar << std::endl;
return 0;
}
What does this strange : bar(num) mean? It somehow seems to initialize the member variable but I've never seen t... | It's a member initialization list. You should find information about it in any good C++ book.
You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).
The takeaway point from the FAQ entry is that,
All other thin... |
1,712,047 | 1,712,295 | Overloading the ostream << operator for a static class? | I have a (simplified) static global class and << operator overload as follows:
class Global
{
private:
static int counter;
Global(){};
public:
friend ostream& operator<<(ostream &out, Global &global);
}
ostream& operator<< (ostream &out, Global &global)
{
//... do output
return out;
}
I w... | First of all, you cannot use a class name as a value - it simply isn't one. So you'll have to introduce a different name for use with << - say, global (with lowercase "g").
In general, if you want to introduce a "streamable" name without defining an object, you should write a stream manipulator:
std::ostream& foo(std::... |
1,712,263 | 1,712,269 | How can I create memory dumps and analyze memory leaks? | I need to get the following to analyze a memory leak issue. How to do that?
Orphan Block Addresses Orphan Call
Stack
Are there any good resources/tools to know about/fix memory leaks.
Thanks
| If you're on linux, use valgrind. It's your new best friend. I'm not sure what tools are available for Windows.
|
1,712,407 | 1,712,431 | Can't include dynamic library header file in more than one file? | I have successfully added a dynamic library to a program, but when I try to include the header file in a second file of the project I get errors about class redeclaration. I will add more info if this isn't enough
| You need to put guards into your header so it isn't included multiple times. For file 'my.h', you can add something along the lines of:
#ifndef MY_H
#define MY_H
// Header declarations here
#endif
This way, you can include the .h file multiple times but it will only be included the first time.
|
1,712,411 | 1,714,063 | QtScript -- script-side callback through C++-side implementation | The solution may be simple. Then again it may not be possible.
I have the base callback class:
class CFCallback {
int command_;
int transfer_rate_;
public:
CFCallback(int command, int transfer_rate = 0) {
command_ = command; transfer_rate_ = transfer_rate; }
virtual ~CFCallback() {}
virt... | I'm afraid it won't work the way you've set it up.
If you want to be able to create the callback in javascript, you need a QObject with an accessible GetVersion(QScriptValue) which the script will the use to pass a script-based implementation of the callback. Note, though, that the callback will not be able to work wit... |
1,712,562 | 1,712,577 | Isn't there a point where encapsulation gets ridiculous? | For my software development programming class we were supposed to make a "Feed Manager" type program for RSS feeds. Here is how I handled the implementation of FeedItems.
Nice and simple:
struct FeedItem {
string title;
string description;
string url;
}
I got marked down for that, the "correct" example an... | It's an issue of "best practice" and style.
You don't ever want to expose your data members directly. You always want to be able to control how they are accessed. I agree, in this instance, it seems a bit ridiculous, but it is intended to teach you that style so you get used to it.
It helps to define a consistent i... |
1,712,641 | 1,717,575 | Boost.Asio documentation is non-existent. What do these errors mean? | I'm struggling with two errors with Boost.Asio.
The first occurs when I try to receive data on a socket:
char reply[1024];
boost::system::error_code error;
size_t reply_length = s.receive(boost::asio::buffer(reply, 1024), 0, error);
if (error) cout << error.message() << endl; //outputs "End of file"
The second occurs ... | This is not a complete solution to your second problem by any means. Any errors that it generates should be mapped into a boost::system::error_code, but I don't find anything like it in boost/system/error_code.hpp, so I'm at a loss as to what exactly it is supposed to mean.
But, after looking through the code for boos... |
1,712,667 | 1,712,674 | What does "#include <sndfile.h>" mean? | What does "#include <sndfile.h>" mean? (Sorry I'm c\c++ nub)
By the way I know ActionScript and HTML.
| That is a preprocessor directive to include the header file called 'sndfile.h'. Basically it means include the contents of that file in the place of that directive, which will usually give you function definitions for an object file that will be linked with your source code, and often defines constants, etc....
See wik... |
1,712,696 | 1,713,128 | Boost::Regex DOTALL flag | Is there a DOTALL matching flag for boost::regex? The documentation shows:
static const match_flag_type match_not_dot_newline;
static const match_flag_type match_not_dot_null;
but no mention of regular DOTALL.
I'm trying to match a python regular expression written as
re.compile(r'<a(.*?)</a>', re.DOTALL)
| I think what you're looking for is the mod_s syntax_option_type. You can also use the inline modifier, (?s).
|
1,712,701 | 1,712,714 | Is boost::make_shared obsolete now? | Is boost::make_shared obsolete now? Haven't found its definition in 1.35.
| Its in the 1.4 docs: http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/make_shared.html
It appears to have been added in version 1.39
|
1,712,713 | 1,712,754 | CUDA: NVCC gives controlling expression is constant warning on assert | I get the warning controlling expression is constant on assert statement like this:
assert(... && "error message");
Why this warning on this assert? How can I suppress this warning?
NVCC is the NVIDIA cuda compiler, I think it is based on LLVM. Why does it give this warning, when the same compiles fine with GCC or Vis... | A portable alternative (possibly wrapped in a macro) would be something like:
{
const bool error_message = true;
assert([...] && error_message);
}
To clear up what i meant:
#define myAssert(msg, exp) { const bool msg(true); assert(msg && (exp)); }
// usage:
myAssert(ouch, a && b);
... gives e.g.:
asserti... |
1,712,753 | 1,712,776 | C++ Win32 API Controls messages | im starting with Win32 api, im adding a button control to my main window with the flowing code:
HWND boton = CreateWindow(
"BUTTON", //
"Caption", //
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles.
250, // x position.
10, // y position.
100, /... | To assign it an ID, you have to use the hMenu parameter. If you have specified that the window will be a child (i.e. with WS_CHILD), the hMenu parameter will be interpreted as an integer ID for the window. Also, provide the BS_NOTIFY style.
HWND boton = CreateWindow (
"BUTTON",
WS_TAPSTOP | WS_VISIBLE | WS_CH... |
1,712,756 | 1,712,803 | "g++" and "c++" compiler | I just found on my Ubuntu, there are two different C++ compilers: /usr/bin/g++ and /usr/bin/c++. I am not familiar with the latter, but man c++ just jumps to the manpage of gcc. I wonder what is their difference as C++ compilers?
| This is typical Ubuntu symlink mayhem.
If you ls -l /usr/bin/c++, you will see it is actually a symbolic link. to:
/etc/alternatives/c++
Which in turn, is also a symbolic link to:
/usr/bin/g++
So, on Ubuntu systems, c++ is g++. The reasoning behind the link indirection is that there are multiple packages that could p... |
1,712,801 | 1,712,813 | C++ Threadsafe Singleton (NOT FOR INIT) | So I want to access a singleton class from multiple threads. Conceptually I'd think that calling non-const methods on this singleton instance would be not thread-safe. I've been looking online and no one seems to address this possible issue. Is there an actual problem with this, is the only issue with Singleton's threa... | You are correct, calling a non-const methods or methods that depend on instance data that could be modified by other threads must be syncronized.
|
1,713,120 | 1,713,181 | C/C++ Integer Operation | I found by chance that
int a = (h/2)*w+ ( (h+1)/2-h/2 ) * (w+1)/2 ;
is equal to
int b = (w * h + 1) / 2 ;
when w and h are positive integers (assume no overflow).
Can you show me why these 2 are the same?
edit : integer -> positive integer.
| Actually this is a math problem: (integer)/2 should be interpreted as floor. So, the problem is:
Show that floor(h/2)*w + ( floor((h+1)/2) - floor(h/2) ) * floor((w+1)/2) is equivalent to floor((w*h+1)/2)
Proof:
h = 2k, w = 2l: (both numbers are even) ...
h = 2k + 1, w = 2l: ...
h = 2k, w = 2l + 1: ...
h = 2k + 1, w... |
1,713,171 | 1,713,427 | Getting return value from a boost::threaded member function? | I have a worker class like the one below:
class Worker{
public:
int Do(){
int ret = 100;
// do stuff
return ret;
}
}
It's intended to be executed with boost::thread and boost::bind, like:
Worker worker;
boost::function<int()> th_func = boost::bind(&Worker::Do, &worker);
boost::thread th(th_func);
th.jo... | I don't think you can get the return value.
Instead, you can store the value as a member of Worker:
class Worker{
public:
void Do(){
int ret = 100;
// do stuff
m_ReturnValue = ret;
}
int m_ReturnValue;
}
And use it like so:
Worker worker;
boost::function<void()> th_func = boost::bind(&Worker::Do, &wo... |
1,713,214 | 1,721,230 | How to use C++ in Go | In the new Go language, how do I call C++ code? In other words, how can I wrap my C++ classes and use them in Go?
| Update: I've succeeded in linking a small test C++ class with Go
If you wrap you C++ code with a C interface you should be able to call your library with cgo (see the example of gmp in $GOROOT/misc/cgo/gmp).
I'm not sure if the idea of a class in C++ is really expressible in Go, as it doesn't have inheritance.
Here's ... |
1,713,218 | 1,713,232 | Fastest way to read a file line by line with an arbitrary number of characters in each | Ok, I'm trying to figure out which way would be faster to read a text file that I'm working with. The contents of the file look like this
1982 3923 3542 4343
2344 3453 2
334 423423 32432 23423
They're basically just an arbitrary number of int numbers and I need to read line by line. Would it be better to use getline ... | I would keep it real simple:
ifstream in(...);
string line;
while (getline(in, line)) {
istringstream line_in(line);
while (line_in) {
int val = 0;
if (line_in >> val) {
// Do something with val
}
}
// eol
}
|
1,713,468 | 1,713,502 | Constructor with custom classes as arguments, throws 'No matching function for call to...' | I'm trying to create a constructor for a custom type, but for some reason, it's trying to call, what I'm guessing is the constructor in the constructor definition of another class.. Couldn't find anything which fits the same symptoms I'm having in any other questions, also as I may not know what I'm looking for.
When I... | In your class you have two instances of LatLng objects. In order to construct your object, the compiler also needs to construct them.
class LatLngBounds {
private:
LatLng northEast;
LatLng southWest;
Since class LatLng does not have a default constructor, you need to explicitly tell the compiler how to constr... |
1,713,476 | 1,713,494 | How should C++ methods that manipulate static data members be defined? | I have a C++ class which contains only static data members.
I noticed the compiler is OK if I define the access methods as const, as static, or as "regular" - so all seem to work.
My question is what is the correct/better practice in this case?
Thanks!
| Static accessors for static data members.
|
1,713,653 | 1,713,711 | BOOST_FOREACH & templates without typedef | When I work with BOOST_FOREACH, there isn't a problem with simple templates as vector. But when I try to iterate through map > for example I need to typedef the element type.
Is there any workaround?
| There is a problem because it is a macro, and therefore cannot handle types containing commas (preprocessor doesn't know about templates).
You can also declare the variable before the loop, see documentation.
std::map<int, double> my_map;
//1)
typedef std::pair<int, double> MyPair;
BOOST_FOREACH(MyPair p, my_map) { .... |
1,713,657 | 1,713,818 | Wrapping dynamic array into STL/Boost container? | I need to wrap a dynamically allocated array(from a = new double[100] for example) into std::vector(preferably) without copying the array.
This restriction is imposed by that the array I want to wrap is mmaped from a file, so just doing vector(a, a+size) will double the memory usage.
Is any tricks to do that?
| One of the best solutions for this is something like STLSoft's array_proxy<> template. Unfortunately, the doc page generated from the source code by doxygen isn't a whole lot of help understanding the template. The source code might actually be a bit better:
http://www.stlsoft.org/doc-1.9/array__proxy_8hpp-source.ht... |
1,713,790 | 1,717,124 | QT drawing without erasing widget | I have a QWidget-derived class. In the constructor I say:
setPalette(QPalette(QColor(250,250,200)));
setAutoFillBackground(true);
Then in my widget's paintEvent() I say:
QPainter painter(this);
painter.drawRect(1,2,3,4);
There is also an updateNow() slot...which just calls update(). How can I make sure my palette d... | I don't have any problems with the following:
#include <QApplication>
#include <QWidget>
#include <QPalette>
#include <QPaintEvent>
#include <QPainter>
class Test : public QWidget
{
public:
Test()
{
setPalette(QPalette(QColor(250, 250, 200)));
setAutoFillBackground(true);
}
protected:
virtual void pai... |
1,714,168 | 1,714,881 | GStreamer gst_element_factory_make fails | I'm trying out a GStreamer test application, but at runtime the following line fails:
demuxer = gst_element_factory_make ("oggdemux", "ogg-demuxer"); // returns NULL
I am using MacOSX and installed GStreamer, libogg and vorbis-tools through MacPorts. So I don't see why it fails.
Any suggestions on how to make it work?... | Reading gstelementfactory.c (GStreamer version 0.10.25) line 463 (gst_element_factory_make function definition), there are three errors which cause a NULL return:
The first argument ('factoryname') is NULL (obviously OK in your code)
The named element factory could not be found (the function gst_element_factory_find r... |
1,714,539 | 1,714,621 | Problem with libraries using winsock.h | I have a project that uses Boost.Asio and the Media-Decoding-Samples that come with the Intel IPP-Library. The problem is the following. If I compile the project without defining WIN32_LEAN_AND_MEAN, Asio complains with the infamous "winsock.h already included" error. If I define the macro, a header in the other librar... | you can get around this if you split up your source and make sure not to use some kind of common header in your application in which you incude both Asio and IPP. So the source files needing Asio include Boost headers, the source files needing IPP include the IPP headers, but the header files for your classes that need... |
1,714,593 | 1,714,671 | C++ - is a pointer to a single value same as a size 1 dynamic array? | I have this snippet of code which I am considering to simplfy:
if (numberOfResults > 1)
{
trackResult_ = new TrackResult[numberOfResults];
for (int i=0; i < numberOfResults; i++)
{
// Make a deep copy
TrackResult tempResult = result[i];
TrackResult * clone = new Tra... | The array of size 1 does not need to be a special case.
When you allocate a dynamic array you are given a pointer to the first element. If the array is of size 1, this is pretty much indistinguishable from just having allocated a single instance of the object.
Your special case usage would work if you changed the . to... |
1,714,874 | 1,714,974 | Is returning a temp-object by reference possible | is it possible to return a reference from a function like in this example code:
string &erase_whitespace(string &text)
{
text.erase(**etc.**);
return text;
}
Call:
string text = erase_whitespace(string("this is a test"));
cout << test;
Does this code work? On Visual C++ it does not crash but it looks wrong.
T... | From § 12.2.3 of the C++ 2003 standard (draft)
Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.
§ 12.2.4:
There are two contexts in which temporaries are destroyed at a different point than the end of the full-
ex... |
1,715,183 | 1,715,232 | Ill formed code snippets | can somebody please tell me the difference between the following two code snippets:
//Code snippet A: Compiles fine
int main()
{
if(int i = 2)
{
i = 2 + 3;
}
else
{
i = 0;
}
}
//Code Snippet B: Doesn't compile :(
int main()
{
if((int i = 2))
{
i = 2 + 3;
}
... | Section 6.4 of the C++ standard (draft n2914 of c++0x) has this to say about the format of if statements:
Selection statements choose one of several flows of control.
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
... |
1,715,195 | 1,715,258 | How to create a Visual Studio 2008 C++ project template? | I've used the "Export Template" feature numerous times for C#, ASP.NET, WinForms, etc. projects. Today I tried to do it for a C++ project and noticed "Export Template" was grayed out in the File-menu.
Is it not possible to create C++ template projects in VS 2008 ?
| yes it is: the ones you see already when creating a new project are in $VsInstallDir)/vcprojects. To create one yourself, you basically create a .vsz and a.vsdir file in which you describe your project template, a bunch of script/html files for your own wizard, and the template files itself (.vcproj, additional content... |
1,715,304 | 1,715,350 | Generating n-digit numbers sequenced by sum of individual digits (without recursion) | I'm looking to generate all possible values of n-digit number, in the following order, where the sequence is dictated by the sum of the individual digits.
For example, with n = 3:
111 sum = 3
112 sum = 4
121
211
122 sum = 5
212
221
113
131
311
114 sum = 6
141
411
:::
999 sum = 27
The order within t... | You can always turn a recursive problem into an iterative one if you maintain your own stack of important data - that's if the reason for avoiding recursion is that the language doesn't support it.
But, if the language does support it, then recursive solutions are far more elegant.
The only other reason I can think of ... |
1,715,390 | 1,715,527 | Should I use a const reference or a boost::shared_ptr? | I have created some C++ classes to model a Solitaire game as a learning exercise.
I have classes for the SolitaireGame, a CardStack (one of the 10 piles of cards on the board ) and a Card. My current model states that the SolitaireGame owns a vector of 104 Card objects - which I call the 'shoe'. The SolitaireGame also... |
The reason being that objects stored in vectors can have their addresses moved about, so storing their addresses anywhere is a no-no.
Storing (const) references is just as bad as storing pointers for the same reason. If the size of the vector does not change as long as other objects hold pointers to the objects there... |
1,715,626 | 1,715,652 | Is it possible to set an application's windows compatibility mode at run-time? | We are using a 3rd party library that sometimes does not work correctly on Win7. WE know how to configure this at installation time, but we'd also like to consider setting it at run time. Is this possible, or does that context have to be set prior to launch? (I think there is a slim to none chance, but figured I wou... | The compatibility settings can't be changed once the application is running.
However, what you could do is have a launcher application that makes sure the compatibility settings are correct and then launches your application. Of course, you need to make sure the launcher application doesn't have compatibility problems.... |
1,715,674 | 1,715,709 | boost bind compilation error | class A
{
bool OutofRange(string& a, string& b, string c);
void Get(vector <string>& str, string& a, string& b);
}
void A::Get(vector <string>& str, string& a, string& b)
{
str.erase(
std::remove_if (str.begin(), str.end(), BOOST_BIND(&A::OutOfRange, a, b, _1)),
str.end()
)... | A::OutOfRange is a function of 4 arguments - implicit *this being the first argument, which is missing in your bind clause
|
1,715,714 | 1,715,914 | Is there a better way? While loops and continues | There are many functions within the code I am maintaining which have what could be described as boilerplate heavy. Here is the boilerplate pattern which is repeated ad nausea throughout the application when handling DB I/O with a cursor:
if( !RowValue( row, m_InferredTable->YearColumn(), m_InferredTable->YearName(), m... | Okay, from what you've said, you have a structure something like this:
while (row!=NULL) {
if (!x) {
GetNextRow();
continue;
}
else {
SetType(someType);
SetValue(someValue);
}
if (!y) {
GetNextRow();
continue;
}
else {
SetType(SomeOtherType);
... |
1,716,274 | 1,717,015 | Fill the holes in OpenCV | I have an edge map extracted from edge detection module in OpenCV (canny edge detection). What I want to do is to fill the holes in the edge map.
I am using C++, and OpenCV libraries. In OpenCV there is a cvFloodFill() function, and it will fill the holes with a seed (with one of the location to start flooding). Howev... | According to the documentation of imfill in MATLAB:
BW2 = imfill(BW,'holes');
fills holes in the binary image BW.
A hole is a set of background pixels that cannot be reached by filling in the background from the edge of the image.
Therefore to get the "holes" pixels, make a call to cvFloodFill with the left corner... |
1,716,363 | 1,716,418 | First chance exception - long at memory location? | What is this and how can I handle/fix it?
First-chance exception at 0x756fb727 in Program.exe:
Microsoft C++ exception: long at memory location 0x0018f7a4.
I am getting about a thousand of these each time I run my application. How can I track this down and fix it/
| In visual studio go to the Debug menu and select "Exceptions...". Turn on all the first chance exception handlers (they default to off).
Now when you run in the debugger it will break at the point the exception is thrown.
|
1,716,456 | 1,716,722 | Lisp as a Scripting Language in a C++ app | Hey, I've been looking at the possibility of adding a scripting language into my framework and I heard about Lisp and thought I would give it a go. Is there a VM for Lisp like Lua and Python or am I in the wrong mindset. I found CLISP here, http://clisp.cons.org/, but am not sure if this is what I am looking for.
Can a... | CLISP is just one implementation of Common Lisp. It's a very good implementation, and it does have some support for being embedded in other (C-based) programs, but that's not its focus and it's GPLed, which may or may not be a deal-breaker for you.
You might be interested in checking out ECL. This implementation is sp... |
1,716,472 | 1,841,769 | Using libtool to load a duplicate function name from a shared library | I'm trying to create a 'debug' shared library (i.e., .so or .dll file) that calls another 'real' shared library that has the same C API as the debug library (in this case, to emulate the PKCS#11 API). However, I'm running into trouble where the link map of the debug library is colliding with that of the real library a... | I haven't found a good way to use libtool to solve this problem yet, but there's a way to avoid the Solaris-specific 'dlmopen' function by using dlopen with these flags:
void *handle = dlopen("realsharedlibrary.so", RTLD_NOW | RTLD_GROUP | RTLD_LOCAL)
Apparently, the problem of symbol-collisions is solved by using RTL... |
1,716,485 | 1,716,654 | Coding practices in C++, what is your pick and why? | I have a big object say MyApplicationContext which keeps information about MyApplication such as name, path, loginInformation, description, details and others..
//MyApplicationCtx
class MyApplicationCtx{
// ....
private:
std::string name;
std::string path;
std::string desciption;
... | Short answer:
Q1: Given the size of your MyAppCtx class, yes, a significant performance hit will take place if the data is dealt with very frequently.
Q2: Minimal, you're passing a pointer.
Q3: Neither, for large objects like that you should use reference semantics and access the data through accessors. Don't worry abo... |
1,716,885 | 1,716,941 | get number of CPUs in C++ MFC application | I write a little raytracer and i'd like to query how many cpu cores (or virtual cpu cores if the cpu uses hyperthreading) the current computer offers, such that i can instanciate as many threads to get better parallel rendering.
How can I do that using C++?
thanks!
| You can get the number of physical processors by calling GetSystemInfo and checking the dwNumberOfProcessors field of the SYSTEM_INFO structure. You can get the number of logical processors by calling GetLogicalProcessorInformation.
|
1,717,023 | 1,717,149 | Is this a design flaw? | Consider two classes
class A{
public:
A(){
}
~A(){
}
};
class AImpl : public A{
public:
AImpl(){
a = new AInternal();
}
AImpl(AInternal *a){
this->_a = a;
}
~AImpl(){
if(a){
delet... |
I am trying to hide the AInternal's implementation and expose only A's interface.
I think you are trying to do something like factory.
Here is an example:
class IA {
public:
IA() {}
virtual ~IA() {}
virtual void dosth() =0;
};
class Factor... |
1,717,475 | 1,717,628 | Template class with different order or variables (Color/Pixel class) | I got two class templates Color3_t and Color4_t that store 3 and 4 color channels and look like this:
template <typename TYPE>
struct Color3_t
{
TYPE Red;
TYPE Green;
TYPE Blue;
void Zero()
{
Red = Green = Blue = 0;
}
(...)
}
Both templates have several function for inverting, swapping etc.... | You Need to push the type that is stored for red/green/blue down into the Color***_t classes like so:
template <typename TYPE>
struct ColorRGB_t
{
typedef TYPE value_type;
value_type Red;
value_type Green;
value_type Blue;
};
template <typename TYPE>
struct ColorBGR_t
{
typedef TYPE value_type;
val... |
1,717,540 | 1,717,656 | Qt portable IPC: only QSharedMemory? | I'm looking for suggestions about choosing a portable way to achieve local IPC in a robust way, since i'm new to C++ and would like to avoid common pitfalls of fiddling with shared memory and locks; therefore I was thinking about message-passing style ipc.
I was planning to use qt for other reasons anyway, thus i took ... | Take a look at Boost.Interprocess which provides a lot of IPC functionality. I have used the interprocess message_queue that provides a pretty clean and easy way to do what I think you want to do.
|
1,717,650 | 1,717,742 | sort vector by more than 1 field | How do I sort the below code by name, age and score... all three fields
#include <string>
#include <vector>
#include <algorithm>
struct student_t
{
std::string name;
int age, score;
};
bool by_more_than_1_field( student_t const &lhs, student_t const &rhs )
{
// sort by name, age and score
}... | You have to be carefull that your sorting criteria is transitive: if x ' y then y !< x.
If it is not transitive, the sort operation result depends on the ordering of the array before the call, which you probably don't want.
bool by_more_than_1_field( student_t const &lhs, student_t const &rhs )
{
if (lhs.name < rhs... |
1,717,665 | 1,717,707 | C++ throwing compilation error on sizeof() comparison in preprocessor #if | I have this which does not compile with the error "fatal error C1017: invalid integer constant expression" from visual studio. How would I do this?
template <class B>
A *Create()
{
#if sizeof(B) > sizeof(A)
#error sizeof(B) > sizeof(A)!
#endif
...
}
| The preprocessor does not understand sizeof() (or data types, or identifiers, or templates, or class definitions, and it would need to understand all of those things to implement sizeof).
What you're looking for is a static assertion (enforced by the compiler, which does understand all of these things). I use Boost.St... |
1,717,721 | 1,717,955 | Examples of PHP In C++ | Well I want to learn C++ and at the moment I'm only familiar with PHP and Javascript. And I thought a good way to start learning would be to transfer methods in PHP to C++.
So basically I want the code snippets below in C++
The post with the best comments will get a big green tick.
Also, if you know of a good beginners... | never try to learn any complex subject by 'translating' from another one, no matter how well you know the old one.
You'd only get inconsistent concepts, with the limitations of both and the advantages of none.
|
1,717,773 | 1,717,830 | Which sorting algorithm is used by STL's list::sort()? | I have a list of random integers. I'm wondering which algorithm is used by the list::sort() method. E.g. in the following code:
list<int> mylist;
// ..insert a million values
mylist.sort();
EDIT: See also this more specific question.
| The standard doesn't require a particular algorithm, only that it must be stable, and that it complete the sort using approximately N lg N comparisons. That allows, for example, a merge-sort or a linked-list version of a quick sort (contrary to popular belief, quick sort isn't necessarily unstable, even though the most... |
1,717,780 | 1,718,009 | How to programmatically disable the auto-focus of a webcam? | I am trying to do computer vision using a webcam (the model is Hercules Dualpix). I know it is not the ideal camera to use, but I have no choice here.
The problem is the auto-focus makes it hard/impossible to calibrate the camera. Anyone knows a way to disable the auto-focus feature. Or, if someone has an idea to deal... | The Hercules cameras are UVC compliant, so they should work with the DirectShow Interface IAMCameraControl. You can set the focus to a specific value, and use the flags to set that you do not want it to be automatic. You can use IAMCameraControl::Get to poll the current state, because not all cameras do support turn... |
1,717,991 | 1,718,124 | Throwing an exception from within a signal handler | We have a library that deals with many aspects of error reporting. I have been tasked to port this library to Linux. When running though my little test suite, one of the tests failed. A simplified version of the test appears below.
// Compiler: 4.1.1 20070105 RedHat 4.1.1-52
// Output: Terminate called after throw... | Signals are totally different than C++ exceptions. You can't use a C++ try/catch block to handle a signal. Specifically, signals are a POSIX concept, not a C++ language concept. Signals are delivered asynchronously to your application by the kernel, whereas C++ exceptions are synchronous events defined by the C++ st... |
1,718,430 | 2,391,016 | default WM_DESTROY not properly cleaning up child windows | I have a WTL 8.0 SDI application for Windows Mobile 5. In this contrived example below, I create a view, destroy it, then re-create it. But, when it's re-created assertions in the WM_INITDIALOG handler fail because the control's HWND isn't valid.
I note that I can fix this by handling WM_DESTROY in CMyView and manually... | It is not good practice to Create, Destroy and re-Create the same window, you should consider hiding it and reinitializing your contents when showing it again.
Anyhow your code will not ASSERT at re-creation with:
virtual void CMyView::OnFinalMessage(HWND)
{
some_control_.m_hWnd = 0;
}
|
1,718,615 | 1,718,668 | Container of Pointers vs Container of Objects - Performance | I was wondering if there is any difference in performance when you compare/contrast
A) Allocating objects on the heap, putting pointers to those objects in a container, operating on the container elsewhere in the code
Ex:
std::list<SomeObject*> someList;
// Somewhere else in the code
SomeObject* foo = new SomeObject(p... | There is a performance hit when inserting objects instead of pointers to objects.
std::list as well as other std containers make a copy of the parameter that you store (for std::map both key and value is copied).
As your someList is a std::list the following line copies your object:
Foo foo;
someList.push_back(foo); ... |
1,718,854 | 1,718,900 | Correct use of s/rand or Boost::random | I know this kind of question has been asked a few times, but alot of them answers boil down to RTFM, but I'm hoping if I can ask the right question... I can get a quasi-definitive answer for everyone else as well, regarding implementation.
I'm trying to generate a sequence of random numbers in one of the two following ... | With option 2, you shouldn't create a new instance of rng and die for each call.
I'm also not sure if I understand the problem with option 1 correctly: you are calling srand() only once, but each call to rand() gives you the same number? That's.. "unusual". Try to reduce the loop to the minimum, and print the value re... |
1,718,957 | 1,718,980 | When returning a pointer, what to return if it's not found? C++ | I'm not sure what to return as a default?
myDrugs is a private vector<Drug*> container
Drug* DrugDealer::getFirstDrugInSack(DrugType drugtobuy)
{
for (int i = 0; i < myDrugs.size(); i++)
{
if (myDrugs[i]->getType() == drugtobuy)
return myDrugs[i];
}
return 0; // is this right?
}
So... | Returning NULL is Ok. You may also consider passing a pointer to pointer as a parameter and returning boolean value, true if it is found and false if it is not:
bool DrugDealer::getFirstDrugInSack(DrugType drugtobuy, Drug** out)
{
for (int i = 0; i < myDrugs.size(); i++)
{
if (myDrugs[i]->getType() == d... |
1,719,051 | 1,719,073 | array of pointers as function parameter | I have a basic question on array and pointer in C/C++.
Say I have:
Foo* fooPtrArray[4];
How to pass the fooPtrArray into a function?
I have tried:
int getResult(Foo** fooPtrArray){} // failed
int getResult(Foo* fooPtrArray[]){} // failed
How can I deal with pointer array?
EDIT: I once thought the error msg is fro... | Both
int getResult(Foo** fooPtrArray)
and
int getResult(Foo* fooPtrArray[])
as well as
int getResult(Foo* fooPtrArray[4])
will work perfectly fine (they are all equivalent).
It is not clear from your question what was the problem. What "failed"?
When passing arrays like that it normally makes sense to pass the eleme... |
1,719,055 | 1,731,970 | Just Want to know what this error message really means! |
expected unqualified-id before '{'
Where is this error on my code? Thanks everyone!
#include <iostream>
using std::cout;
using std::endl;
//function prototypes
void findsmallest (int[], int &);
void findsmallest (int scores [], int & min);
int main()
{
//declare variables
int smallest = 0;
int scores... | The error is in the first line of the findsmallest() function definition. Get rid of the semicolon and it should work (barring other errors in the code -- I didn't check it for correctness).
void findsmallest(int scores [], int & min); <-------semicolon
{
vs
void findsmallest(int scores [], int & min) <--------no sem... |
1,719,070 | 1,719,155 | What is the right approach when using STL container for median calculation? | Let's say I need to retrieve the median from a sequence of 1000000 random numeric values.
If using anything but std::list, I have no (built-in) way to sort sequence for median calculation.
If using std::list, I can't randomly access values to retrieve middle (median) of sorted sequence.
Is it better to implement sorti... | Any random-access container (like std::vector) can be sorted with the standard std::sort algorithm, available in the <algorithm> header.
For finding the median, it would be quicker to use std::nth_element; this does enough of a sort to put one chosen element in the correct position, but doesn't completely sort the cont... |
1,719,096 | 1,719,133 | How can I receive emails in C++ via POP3? | I've been trying to find a POP3 C++ client on the internet but I haven't found any luck.
We are working on a project for school that is essentially a C++ course (so I can't use C#...), and we are making a Email client that has to support sending and receiving emails and attachments. We are also working with .NET (beca... | POCO has POP3- and SMTP-support in its Net-library.
|
1,719,216 | 1,719,230 | static member variable and method | If I have a C++ class which contains a static member variable, does the accessor method for this variable need to be static as well? Also, are there any issues that might occur if I inline this method?
| It doesn't need to be static, but unless it's doing something specific to a particular instance of the class, there's no real reason not to make it static anyway.
This shouldn't effect inlining in any way.
|
1,719,325 | 1,730,862 | FLTK in Cygwin using Eclipse (Linking errors) | I have this assignment due that requires the usage of FLTK. The code is given to us and it should compile straight off of the bat, but I am having linking errors and do not know which other libraries I need to include.
I currently have "opengl32", "fltk_gl", "glu32", and "fltk" included (-l), each of which seem to redu... | Sorry for the lack of closure, but I just booted into my Linux netbook and got it working.
-lfltk -lfltk_gl -lGLU -lGL -lXext -lX11 -lm
|
1,719,358 | 1,719,893 | How can I manage a group of derived but otherwise Unrelated Classes | It seems the more I talk about this problem the better I understand it. I think my previous question didn't convey what I am trying to do correctly. My apologies for that.
In my design I have GameObjects which are essentially an aggregation class, all functionality in a GameObject is implemented by adding various "Feat... | The other answer was getting too bloated with edits, so I started a new one.
The casting you are doing in the receiveMessage() functions is definitely a code smell.
I think you need to use a combination of:
Abstract factory pattern to instantiate your objects (messages and components)
Observer pattern to respond to me... |
1,719,501 | 1,719,528 | How do I convert a c++ string to a .NET String^? | I've been trying to figure out how to convert a string to a String in Visual Studio 2005 with no luck.
Here is the relevant code:
#include <string>
using namespace std;
#using <System.dll>
using namespace System;
string test = "a test string";
So I'm trying to convert test into a String^ to use inside other .NET clas... | String^ str = gcnew String(test)
|
1,719,530 | 1,719,540 | Can an ifstream variable be a global variable? | // stream from file.
ifstream file;
int main (int argc, char * argv[]) {
// get argument passed from command line
// This is file name
if (argc != 2 ) {
cout << "use: ./executable <filename>";
}else {
//cout << "You are using filename: " << argv[1];
// start the file stream
file (argv[1]);
}
Is th... | You're trying to call the ifstream's () operator (which doesn't exist), when you should be using file.open(argv[1]).
Besides that, there's nothing illegal about having a global ifstream.
|
1,719,607 | 1,719,647 | Is the memory allocated by new operated consecutive? | as the title says, I want to know in c++, whether the memory allocated by one new operation is consecutive...
| BYTE* data = new BYTE[size];
In this code, whatever size is given, the returned memory region is consecutive. If the heap manager can't allocate consecutive memory of size, it's fail. an exception (or NULL in malloc) will be returned.
Programmers will always see the illusion of consecutive (and yes, infinite :-) memor... |
1,719,818 | 1,719,847 | Difference between reference and const reference as function parameter? | Here is a simple snippet of C++ code:
A foo(){
A a; // create a local A object
return a;
}
void bar(const A & a_r){
}
bar(foo());
Why does the argument of function bar have to be a const reference,not just a reference?
Edit1: I know that reference is to avoid copying overhead. and const is for read-only. But h... | Without the error message, I'm not exactly sure what the compiler might be complaining about, but I can explain the reason logically:
In the line:
bar(foo());
The return value of foo() is a temporary A; it is created by the call to foo(), and then destructed as soon as bar() returns. Performing a non-const operation ... |
1,719,928 | 1,719,952 | Why is this syntax invalid? vectorPointer->[0] | In C++, why is the following element access in a vector invalid?
void foo(std::vector<int>* vecPtr) {
int n = vecPtr->size(); // ok
int a = vecPtr->[0]; // invalid
}
Instead, we have to write the more cumbersome
(*vecPtr)[0] = 1;
I think, the operator[] call should just have the same syntax like a method cal... | It's because the language expects a member to appear after ->. That's how the language is made up. You can use the function call syntax, if you like
// not really nicer
vecPtr->operator[](0);
If you have to do this a lot in sequence, using [0] instead of the parentheses can improve readability greatly
vecPtr[0][0]
Ot... |
1,720,271 | 1,720,335 | C++ Server is terminating if the front end Tomcat is killed. Error "Received untrapped signal [13] - SIGPIPE" | I am facing a problem in my C++ server program. The request XML comes from the front end (Java) and the back end server (C++) process the request and returns the reply XML.
As part of testing after submitting the request to back-end we killed the Tomcat server. The back-end application (threaded server application) aft... | The easiest thing to do is just ignore the signal:
struct sigaction new_action, old_action;
/* Set up the structure to specify the new action. */
new_action.sa_handler = SIG_IGN;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction(SIGPIPE, &new_action, &old_action);
Once you do this, the read or wr... |
1,720,609 | 1,930,851 | Supporting multi-add/delete (and undo/redo) with a QAbstractItemModel (C++) | Greetings,
I've been writing some nasty code to support the undo/redo of deletion of an arbitrary set of objects from my model. I feel like I'm going about this correctly, as all the other mutators (adding/copy-pasting) are subsets of this functionality.
The code is nastier than it needs to me, mostly because the only ... | Think of beginRemoveRows/endRemoveRows, etc. as methods to ask the QAbstractItemModel base class to fix up your persistent model indexes for you instead of just a way of updating views, and try not to confuse the QAbstractItemModel base class in its work on those indexes. Check out http://labs.trolltech.com/page/Projec... |
1,720,712 | 1,720,734 | Speed difference: separate functor VS operator() inside a big class with *this | I'm using the c++ STL heap algorithms, and I wrote a wrapper class around it so I could do some other stuff. When I tried to use the code below, for example:
//! Min-heap wrapper class.
class FMMHeap{
public:
FMMHeap(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) >... | I'm not certain: but maybe pop_heap ends up copying the functor object you pass in.
The copy for your FMMHeap would be more expensive than the simple HeapSort
|
1,720,953 | 1,720,994 | Why not resize and clear works in GotW 54? | Referring to article Gotw 54 by HerbSutter, he explains about
The Right Way To "Shrink-To-Fit" a
vector or deque and
The Right Way to Completely Clear a vector or
deque
Can we just use container.resize()
and container.clear() for the above task
or am I missing something?
| There are two different things that a vector holds: size Vs capacity. If you just resize the vector, there is no guarantee that the capacity(how much memory is reserved) must change. resize is an operation concerned with how much are you using, not how much the vector capacity is.
So for example.
size == how much y... |
1,721,241 | 1,721,396 | What programming language is IIS written in? | I'd like to know this information for IIS versions 6.0, 7.0 and 7.5.
| It is made in C++, microsoft has given isapi extension which is api for IIS and programmers can explore classes using this api
|
1,721,351 | 1,721,526 | How can I measure the execution time of a for loop? | I want to measure the execution time of for loops on various platforms like php, c, python, Java, javascript... How can i measure it?
I know these platforms so i am talking about these:
for (i = 0; i < 1000000; i++)
{
}
I don't want to measure anything within the loop.
Little bit modification:
@all Some of the ... | Note that it also depends on what exactly you want to achieve: do you care about the time your program waits due to it being preempted by the system scheduler? All the solutions above take actual time elapsed into consideration, but that also involves the time when other processes run instead of your own.
If you don't ... |
1,721,488 | 1,721,535 | c++ array access through pointer | A simple question about accessing array information through pointers that I can't seem to figure out. I'm passing a bunch of multi-dimentional arrays into a function. Now they are not dynamic but even if static, I have to pass them as pointers right? (If I'm wrong, please do correct me)
So once I do pass them into a fu... | If your arrays are of fixed size, you can do it this way:
void foo(int arr[5][5])
{
cout << arr[2][2] << endl;
}
|
1,721,543 | 1,721,575 | Continue to debug after failed assertion on Linux? | When an assertion fails with Visual C++ on Windows, the debugger stops, displays the message, and then lets you continue (or, if no debugging session is running, offers to launch visual studio for you).
On Linux, it seems that the default behavior of assert() is to display the error and quit the program. Since all my a... | You really want to recreate the behavior of DebugBreak. This stops the program in the debugger.
My googling of "DebugBreak linux" has turned up several references to this piece of inline assembly which is supposed to do the same.
#define DEBUG_BREAK asm("int $3")
Then your assert can become
#define ASSERT(TEST) if(!(T... |
1,721,834 | 1,721,943 | C++ STL unordered_map problems and doubts | after some years in Java and C# now I'm back to C++. Of course my programming style is influenced by those languages and I tend to feel the need of a special component that I used massively: the HASH MAP. In STL there is the hash_map, that GCC says it's deprecated and I should use unordered_map. So I turned to it. I co... | Just use:
actionControllers[ actionArr[i] ] = controller;
this is the operator overloading java owe you for ages :)
|
1,721,980 | 1,722,022 | Calculating variance with large numbers | I haven't really used variance calculation that much, and I don't know quite what to expect. Actually I'm not too good with math at all.
I have a an array of 1000000 random numeric values in the range 0-10000.
The array could grow even larger, so I use 64 bit int for sum.
I have tried to find code on how to calc varian... | Note: It doesn't look like you're calculating the variance.
Variance is calculated by subtracting the mean from every element and calculating the weighted sum of these differences.
So what you need to do is:
// Get mean
double mean = static_cast<double>(value_sum)/size;
// Calculate variance
double variance = 0;
for(... |
1,722,260 | 1,722,277 | What creates the stack? | Suppose in a program we have implemented a stack. But who creates the stack ? Is it the processor, or operating system, or compiler?
| If you mean the data structure: The processor executes the code. The code makes calls to the operating system to get the memory for the stack, and then manipulates it to form it into a stack. The compiler just turns the code you wrote into code the processor can understand.
If you mean the execution stack: The OS is re... |
1,722,381 | 1,722,428 | c++ virtual class, subclass and selfreference | consider this class:
class baseController {
/* Action handler array*/
std::unordered_map<unsigned int, baseController*> actionControllers;
protected:
/**
* Initialization. Can be optionally implemented.
*/
virtual void init() {
}
/**
* This must be implemented by subclasses in ... | Your code is trying to embed an entire instance of testController inside itself, which is impossible. Instead, you want a reference:
testController &tc;
or a pointer
testController *tc;
|
1,722,386 | 1,722,551 | xerces-c 2.8 : error while loading shared libraries | I'm trying to compile a program running on an HP UX server on a Red Hat Linux.
It uses xerces-c library to parse xml files. Compilation is ok, but when i try to run it, I get the following message
./a.out: error while loading shared
libraries: libxerces-c.so.28: cannot
open shared object file: No such file
or di... | run ldd a.out and see if the linker can resolve the right .so file
export LD_LIBRARY_PATH to include the current folder (in the same manner as the PATH variable) and check ldd again
|
1,722,387 | 1,722,519 | Looking for an implemenentation of binomial tree in c++ | If anyone can point me into direction where i can find an easy to understand impl. of binomial tree, that would be very helpful. thx
tree should look like in this article: http://software.intel.com/en-us/articles/high-performance-computing-with-binomial-option-pricing-part-1/
| I have used this example in the past to develop a project that required us to use a binomial tree model, however, this example is in C#.
http://www.codeproject.com/KB/recipes/binomialtree.aspx
|
1,722,670 | 1,722,722 | Common way to call mother-class operator= in C++? | Let's suppose I have a class Dog that inherits from class Animal,
you might want to insert a call to Animal::operator= in Dog::operator=.
What is the most readable/common way to write it?
I think I know those two...
static_cast<Animal*>(this)->operator=(other);
and
this->Animal::operator=(other);
| Since you are doing it from within a child class method
Animal::operator=(other);
No need for this->. The scope resolution syntax does exactly what was requested. I don't see a point in doing it "indirectly" with a cast.
Note also that doing it with a cast might not produce the expected result in general case, since i... |
1,722,916 | 1,722,931 | how to link c++ program with HTML page? | i am working on php...!!
Is it possible to link HTML page to c++/c at back end.
means instead of php script i want to run c/c++
if Yes How??
| Check CGI and FastCGI technologies.
|
1,723,084 | 1,723,235 | Does Blitz++ use BLAS routines when it is possible and appropriate to | I know that Blitz++ gets its performance plus by extensive usage of expression templates and template metaprogramms. But at some point you can't get more out of your code by using these techniques - you have to multiply and sum some floats up. At this point you can get a final performance kick by using the highly optim... | Only for benchmarks you must specify it when you configure blitz++:
./configure -with-blas=...
Blitz does not use Blas routines.
|
1,723,229 | 1,723,405 | Which allocator are available in STLPORT, and how to use them | We're using STLPORT and we'd like to change stlport's default allocator:
instead of vector<int>, we'd like to try vector<int, otherallocator>
Which alternative allocator are available in stlport, and what are their features?
How do I use them?
| Take a look here for switching the default allocator. I think you'll find the available allocator implementations are under include/stlport/stl/ in your installation.That said, it's a standard interface and you can implement your own.
|
1,723,288 | 1,723,385 | How to handle different situations in mouse event handler properly? | In my Qt application in the event handler for mouse press events I have such ugly code
void Render::Viewer::mousePressEvent(QMouseEvent* e)
{
switch (e->button())
{
case Qt::LeftButton:
switch (mode_)
{
case Render::Viewer::ModeView:
switch (e->modifiers())
{
case Qt::NoModifier:
... | It would be easier to read and maintain if you broke up tasks into their own functions:
void Render::Viewer::mousePressEvent(QMouseEvent* e)
{
switch (e->button())
{
case Qt::LeftButton:
handleLeftButton(e);
break;
case Qt::RightButton:
handleRightButton(e);
break;
}
}
void Render::Vi... |
1,723,419 | 1,723,520 | Configuration structs vs setters | I recently came across classes that use a configuration object instead of the usual setter methods for configuration. A small example:
class A {
int a, b;
public:
A(const AConfiguration& conf) { a = conf.a; b = conf.b; }
};
struct AConfiguration { int a, b; };
The upsides:
You can extend your objec... | Whether you pass the data individually or per struct is a question of style and needs to be decided on a case-by-case basis.
The important question is this: Is the object is ready and usable after construction and does the compiler enforce that you pass all necessary data to the constructor or do you have to remember ... |
1,723,469 | 1,723,507 | Interface Inheritance in C++ | I have the following class structure:
class InterfaceA
{
virtual void methodA =0;
}
class ClassA : public InterfaceA
{
void methodA();
}
class InterfaceB : public InterfaceA
{
virtual void methodB =0;
}
class ClassAB : public ClassA, public InterfaceB
{
void methodB();
}
Now the following code is not... | That is because you have two copies of InterfaceA. See this for a bigger explanation: https://isocpp.org/wiki/faq/multiple-inheritance (your situation is similar to 'the dreaded diamond').
You need to add the keyword virtual when you inherit ClassA from InterfaceA. You also need to add virtual when you inherit Interfac... |
1,723,515 | 1,723,737 | Insert into an STL queue using std::copy | I'd like to use std::copy to insert elements into a queue like this:
vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
queue<int> q;
copy( v.begin(), v.end(), insert_iterator< queue<int> >( q, q.front() ) );
But this fails to compile, complaining that begin is not a member of std::queue.
Note: I tried it with std::... | Unfortunately std::queue 'adapts' the function known as push_back to just push which means that the standard back_insert_iterator doesn't work.
Probably the simplest way (albeit conceptually ugly) is to adapt the container adapter with a short lived container adapter adapter[sic] (eugh!) that lives as long as the back ... |
1,723,537 | 1,723,667 | Template specialization of a single method from a templated class | Always considering that the following header, containing my templated class, is included in at least two .CPP files, this code compiles correctly:
template <class T>
class TClass
{
public:
void doSomething(std::vector<T> * v);
};
template <class T>
void TClass<T>::doSomething(std::vector<T> * v) {
// Do something... | As with simple functions you can use declaration and implementation.
Put in your header declaration:
template <>
void TClass<int>::doSomething(std::vector<int> * v);
and put implementation into one of your cpp-files:
template <>
void TClass<int>::doSomething(std::vector<int> * v) {
// Do somtehing with a vector of in... |
1,723,572 | 1,723,592 | What is the best solution for suppressing warning from a MS include (C4201 in mmsystem.h) | I am tired of having to look at warnings during our compilations - warnings that come from MS include files.
"C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\mmsystem.h(1840): warning C4201: nonstandard extension used : nameless struct/union"
I have seen this thread that suggests changing the header itself (but t... | Something like
#pragma warning(push, disable: 4201)
#include <mmsystem.h>
#pragma warning(pop)
|
1,723,575 | 1,723,938 | How to perform a bitwise operation on floating point numbers | I tried this:
float a = 1.4123;
a = a & (1 << 3);
I get a compiler error saying that the operand of & cannot be of type float.
When I do:
float a = 1.4123;
a = (int)a & (1 << 3);
I get the program running. The only thing is that the bitwise operation is done on the integer representation of the number obtained after ... | At the language level, there's no such thing as "bitwise operation on floating-point numbers". Bitwise operations in C/C++ work on value-representation of a number. And the value-representation of floating point numbers is not defined in C/C++ (unsigned integers are an exception in this regard, as their shift is define... |
1,723,629 | 1,723,781 | What happens when QueryPerformanceCounter is called? | I'm looking into the exact implications of using QueryPerformanceCounter in our system and am trying to understand it's impact on the application. I can see from running it on my 4-core single cpu machine that it takes around 230ns to run. When I run it on a 24-core 4 cpu xeon it takes around 1.4ms to run. More interes... | Windows QueryPerformanceCounter() has logic to determine the number of processors and invoke syncronization logic if necessary. It attempts to use the TSC register but for multiprocessor systems this register is not guaranteed to be syncronized between processors (and more importantly can vary greatly due to intellige... |
1,723,801 | 1,723,816 | IOServiceAddMatchingNotification issue | void functions::start()
{
io_iterator_t enumerator;
...some code...
result = IOServiceAddMatchingNotification(
mNotifyPort,
kIOMatchedNotification,
IOServiceMatching( "IOFireWireLocalNode" ),
... | What is serviceMatchingCallback? Judging by the error, it seems to be a member function. You can't pass a member function as a callback in this manner. See this recent discussion on calling a class member function from a callback.
|
1,723,977 | 1,724,126 | Accessing protected member functions from test code in C++ | I've been racking my brain trying to think of the best way to access a protected member function from some test code in C++, here's my problem:
//in Foo.h
Class Foo
{
protected:
void DoSomething(Data data);
}
//in Blah.h
Class Blah
{
public:
Foo foo;
Data data;
};
//in test code...
Blah blah;
blah.foo.D... | Ok, since you said it is only a test code I am going to suggest something seriously hacky but would work:
struct tc : protected Foo
{
tc(Foo *foo, Data& data)
{
((tc*)foo)->DoSomething(data);
}
};
Blah blah;
tc t(&blah.foo, blah.data);
|
1,724,009 | 1,724,039 | Why doesn't my custom iterator work with the STL copy? | I wrote an OutputIterator for an answer to another question. Here it is:
#include <queue>
using namespace std;
template< typename T, typename U >
class queue_inserter {
queue<T, U> &qu;
public:
queue_inserter(queue<T,U> &q) : qu(q) { }
queue_inserter<T,U> operator ++ (int) { return *this; }
queue_in... | Your queue_inserter needs to be derived from std::iterator so that all the typedefs such as value_type are properly defined since these are used inside STL algorithms This definition works:
template< typename T, typename U >
class queue_inserter : public std::iterator<std::output_iterator_tag, T>{
queue<T, U> &qu; ... |
1,724,036 | 2,143,606 | Splitting templated C++ classes into .hpp/.cpp files--is it possible? | I am getting errors trying to compile a C++ template class which is split between a .hpp and .cpp file:
$ g++ -c -o main.o main.cpp
$ g++ -c -o stack.o stack.cpp
$ g++ -o main main.o stack.o
main.o: In function `main':
main.cpp:(.text+0xe): undefined reference to 'stack<int>::stack()'
main.cpp:(.text+0x1c): ... | It is not possible to write the implementation of a template class in a separate cpp file and compile. All the ways to do so, if anyone claims, are workarounds to mimic the usage of separate cpp file but practically if you intend to write a template class library and distribute it with header and lib files to hide the ... |
1,724,051 | 1,724,176 | Const correctness for value parameters | I know there are few question about const correctness where it is stated that the declaration of a function and its definition do not need to agree for value parameters. This is because the constness of a value parameter only matters inside the function. This is fine:
// header
int func(int i);
// cpp
int func(const i... | My take on it:
It's not a bad idea, but the issue is minor and your energy might be better spent on other things.
In your question you provided a good example of when it might catch an error, but occasionally you also end up doing something like this:
void foo(const int count /* … */)
{
int temp = count; // can't m... |
1,724,186 | 1,724,514 | C++ std::string and NULL const char* | I am working in C++ with two large pieces of code, one done in "C style" and one in "C++ style".
The C-type code has functions that return const char* and the C++ code has in numerous places things like
const char* somecstylefunction();
...
std::string imacppstring = somecstylefunction();
where it is constructing the... | Probably the best thing to do is to fix the C library functions to their pre-breaking change behavior. but maybe you don't have control over that library.
The second thing to consider is to change all the instances where you're depending on the C lib functions returning an empty string to use a wrapper function that'l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.