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,928,557 | 4,928,626 | How do I create and use a class arrow operator? | So, after researching everywhere for it, I cannot seem to find how to create a class arrow operator, i.e.,
class Someclass
{
operator-> () /* ? */
{
}
};
I just need to know how to work with it and use it appropriately.
- what are its inputs?
- what does it return?
- how do I properly declare/prototype it?
| The operator -> is used to overload member access. A small example:
#include <iostream>
struct A
{
void foo() {std::cout << "Hi" << std::endl;}
};
struct B
{
A a;
A* operator->() {
return &a;
}
};
int main() {
B b;
b->foo();
}
This outputs:
Hi
|
4,928,837 | 4,928,965 | Why include a header and forward declare the class contained in the same cpp file? | I've been looking at the Fear SDK for my university project, but have noticed some code like so:
Foo.h
class Foo
{
public:
int iSomething;
};
Bar.cpp:
#include "Foo.h"
// Forward declarations
class Foo;
Is there any particular reason to forward declare AND include the appropriate header in the same cpp f... | It's more than simply redundant, it's potentially problematic. Say Foo.h changes so Foo becomes a typedef to some particular instantiation of a generic, templatised equivalent - the kind of thing that can be anticipated as part of normal software evolution. Then Bar.cpp's "class X" will needlessly cause a compilation... |
4,928,924 | 5,281,454 | Decreasing memory usage, C, CodeChef | I'm doing this problem: http://www.codechef.com/problems/FCTRL
I have the solution, but, the memory usage is coming out to be 1.6 MB, which, apparently, is too much. I don't understand how I can decrease this seeing that I have almost no persistent data. Here's my code:
#include <stdio.h>
#include <math.h>
int maxPo... | This is what i submitted and it was accepted
#include<stdio.h>
int main()
{
long n,q=0,t,c=1,result,z,m=5;
scanf("%ld",&t);
while(c<=t)
{
scanf("%ld",&n);
z=0;
while(n!=0)
{
q=n / m;
z=z+q;
n=q;
}
printf("%ld\n",z);
c++;
}
return 0;
}
The main logic is that no of zeroes at the end of a factorial is the highest powe... |
4,929,016 | 4,929,135 | HTTP keep-alive with C++ recv winsocket2 | I'm Coding my own HTTP fetcher socket. I use C++ in MVC++ and winsocket2.h
I was able to program the socket to connect to the required website's server and send an HTTP GET request.
Now the problem is after I send an HTTP GET request with Keep-alive connection, I call the recv function , and it works fine except afte... | Check for a Content-Length: xxxxx header, and only read xxxxx bytes after the header, which is terminated by a blank line (CR-LF-CR-LF in stream).
update
If the data is chunked:
Chunked Transfer-Encoding (reference)
...
A chunked message body contains a
series of chunks, followed by a line
with "0" (zero), followed by... |
4,929,255 | 5,021,912 | Building static libraries on Mac using CMake and GCC? | Greetings all,
I have a static library which I later link with my application. My development environment is CMake, GCC (Linux, Mac), MinGW (Windows).
I can compile the static library without any problem on Linux and Windows. (I can even build shared libraries in my application on Mac).
EDIT: I compiled the library as... | The similar problem with static libraries on MacOSX is discussed here: http://lists.macosforge.org/pipermail/macports-tickets/2008-June/010680.html
Try to do a full clean and run a not-parallel build.
And this guide recommends to install macports, then "sudo port install autogen autoconf automake nano libtool libsdl ... |
4,929,487 | 4,929,516 | Memory allocation in c++ |
Possible Duplicate:
Stack,Static and Heap in C++
Hi guys,
I am currently preparing for interviews, and quite often i see questions like, where are "static" variables or where are "local"/"global" variables stored and im totally puzzled.
I'm aware of two kinds of memory: Stack and Heap. Other than this, are there any... | To simplify just a bit, there are basically three main storage areas you need to be concerned with:
Global data -- a single static memory location outside the stack or heap. These are the variables declared not local to any function. (The distinction evident by the C/C++ "static" keyword is really just about which p... |
4,929,537 | 4,929,547 | How can I use boost::bind to bind a class member function? | #include <QtCore/QCoreApplication>
#include <boost/bind.hpp>
#include <boost/function.hpp>
class button
{
public:
boost::function<void()> onClick;
boost::function<void(int ,double )> onClick2;
};
class player
{
public:
void play(int i,double o){}
void stop(){}
};
button playButton, stopButton;
pla... | boost::bind(&player::play, &thePlayer)
You need to use placeholders for the two arguments:
boost::bind(&player::play, &thePlayer, _1, _2)
The placeholders allow you to say "I'm only binding certain arguments; other arguments will be provided later."
|
4,929,616 | 4,929,744 | Calling C++ dll from .Net code is excruciatingly slow when a debugger is attached | I am using VS 2008 to compile and debug my code. In my application, the front end is C#, the backend is C++. I access the C++ code via interop.
One thing I notice is that if I press F5, and I link in the debug version of the native code, it would take more than 20 seconds to run the native code. If I link in the releas... | My best guess would be that loading the debugging symbols is what's slowing you down. I've seen the exact same thing happen with purely unmanaged C++ projects that are set to automatically load the symbol files for all of the Windows system libraries. Make sure that you're not automatically loading debugging symbols:
... |
4,929,869 | 4,929,890 | C++ calling template functions of Base class | Below are two cases.
Case 1) Base->BaseIndirect->DerivedIndirect
Case 2) Base->Derived
In Case 2), I am able to call a template function of Base class using 3 notations.
In Case 1), I am able to call template function of Base class using only 1 of those notations. And, I am NOT able to call template function of Base... | The reason that many of these calls are failing is that there's a syntactic ambiguity you need to resolve using the single most obscure use of the template keyword. Instead of writing
this->fbase<true>(5);
You need to write
this->template fbase<true>(5);
The reason is that without the template keyword, the compiler ... |
4,929,956 | 4,929,986 | Split const char* in C++ | How could I split const char*?
I have a date pattern saved on a const char. I would like to know if it is valid or not.
Since I can't split const char*, what should I do then?
| You can easily use sscanf(), or perhaps strptime() if your system has it, to parse the day/month/year fields from a character buffer. You can also put the text into a std::stringstream then stream the values into numeric variables, ala:
std::istringstream is("2010/11/26");
int year, month, day;
char c1, c2;
if (is >> ... |
4,930,096 | 4,930,250 | C++0x way to replace for(int i;;) range loops with range-based for-loop | So I've been getting into the new C++ using GCC 4.6 which now has range-based for-loops. I've found this really nice for iterating over arrays and vectors.
For mainly aesthetic reasons I wondered if there was a way to use this to replace the standard
for(int i = min; i < max; i++) {}
with something like
for(int& i : ... | I don't see it anywhere. But it would be rather trivial:
class range_iterator : public std::input_iterator<int, int> {
int x;
public:
range_iterator() {}
range_iterator(int x) : x(x) {}
range_iterator &operator++() { ++x; return *this; }
bool operator==(const range_iterator &r) const { return x == r... |
4,930,176 | 4,930,186 | Why would I include iostream and ostream separately? | I've noticed that many people include iostream and ostream in C++ programs separately, like so:
#include <iostream>
#include <ostream>
int main()
{
}
Why would anyone do that? Since iostream inherits from ostream, it should include everything in it, right? Is there some obscure reason? What about simple (std::cout) co... | Although stringstream inherits from iostream, it is not declared in the <iostream> header. The <iostream> header contains the definition of the iostream type along with the famous cout, cerr, cin, and clog types, but not other types that are iostreams (for example, file streams). For these, you do need to explicitly ... |
4,930,309 | 4,930,756 | calling member functions from within another member function of the same class in C++, objective C | Consider the following:
class A{
//data members
void foo()
{
bar();//is this possible? or should you say this->bar() note that bar is not static
}
void bar()
{
}
}//end of class A
How do you call member functions from within another? And how does static functions affect the use o... | Nawaz is correct: 'this' is implicit. The one exception is if foo were a static function, because in static functions there is no 'this'. In that case, you can't use bar() unless bar() is also a static function, and you can't use this->bar() at all.
|
4,930,492 | 4,930,555 | Integer Value Problem |
Possible Duplicate:
How can I pad an int with leading zeros when using cout << operator?
How could I show 01 in an integer?
whenever I convert a string to integer, I always get 1 instead of 01.
How could get a 01 value.
| Since you tagged it as C++, the way to do it with C++'s streams could be the following:
#include <sstream>
#include <iomanip>
#include <iostream>
int main() {
int value = 1;
std::stringstream ss;
ss.width(2);
ss << std::setfill('0') << value;
std::cout << ss.str() << std::endl; // displays '01... |
4,930,894 | 4,931,012 | How can I free built-in data token in static area | How can I free built-in data token in static area over using static keyword after a some time pass or when some condition meet ?
ex;
int func2 ( void ) {
static int i = 0 ;
// some work ;
if ( i == 20 ) {
return i ;
// some thing to give static memory place to memory
}
... | You can't (unless i is an int* and you allocate and delete it manually) but : when you do that static i = 0; at first call you create and initialize i.
When func2 is call second time, this line will be ignore :i already exist.
int func2(void) {
static int i = 0;
std::cout << "i " << i << std::endl;
i += 20... |
4,930,913 | 4,930,935 | Time error wrong output | time_t ltime;
time( <ime );
tm * pTm = localtime(<ime);
printf("%d",pTm->tm_wday);
output= 2 , how come while 2day is 8 -.- anyclue?
| tm_wday is the weekday, indexed from 0 being Sunday, to 6 being Saturday.
It is 2 today because it's a Tuesday.
What you want to access for the day of the month is tm_mday.
See also:
Members of struct tm explained
|
4,931,188 | 4,931,464 | How to get __declspec(thread) working on Windows CE | I have a class containing:
class SomeClass {
SomeClass *previous;
static __declspec(thread) SomeClass *stackTop;
public:
SomeClass() : previous(stackTop) { stackTop = this; }
~SomeClass() { stackTop = previous; }
};
__declspec(thread) SomeClass *SomeClass::stackTop = NULL;
This compiles fine for Win3... | I don't believe that version of Pocket PC (Windows CE) supports the __declspec(thread) attribute (TLS). It would explain why this only comes up when you're compiling for Pocket PC but not for Win32. See the following links:
Windows CE does not
support the __declspec(thread)
attribute
__declspec (thread) returns
error
... |
4,931,193 | 4,931,315 | CPP unit setup for C++ | In CPP unit we run unit test as part of build as part of post build setup. We will be running multiple tests as part of this. In case if any test case fails post build should not stop, it should go ahead and run all the test cases and should report summary how many test cases passed and failed. how can we achieve this.... | Your question is too vague for a precise answer. Usually, a unit test engine return a code to tell it has failed (like a non zero return code in the shell on linux) or generate some output file with results. The calling system handle this. If you have written it (some home made scripts) you have to give the option to g... |
4,931,425 | 4,932,189 | How do I unit test a factory? | I unit test my classes by giving all my classes an interface. These interfaces have in turn their own mocks.
But lets say I have the following:
class IData
{
GetData()
}
class IOnScreenDataCalculator
{
Calculate(IData)
}
class OnScreenData : IOnScreenData
{
OnScreenData(PTR_T(IData), PTR_T(IOnScreenDataCalculat... | I am not sure the code snippets are really c++, but the example should be something like this :
class ExampleIface
{
public:
virtual ~ExampleIface() {}
virtual void a() = 0;
};
class Example1: public ExampleIface
{
public:
virtual ~Example1() {}
virtual void a()
{
// something
}
};
c... |
4,931,549 | 4,931,587 | c++ PRINT macro linux - add date and time | in my c++ linux application I have this macro:
#define PRINT(format,arg...) printf(format,##arg)
I want to add a date and time to the beggining of the string that come to PRINT. (it is a log, so I want it at runtime, with variables)
how to change this macro in order to do it?
thanks
| Do you want compile time or runtime added to the string? If the former:
#define PRINT(format,arg...) printf(__DATE__ ":" __TIME__ " " format,##arg)
will work most of the time.
Note that this will only work if invocations of PRINT only use a string literal for the format string. (ie, PRINT( "foo" ) will work, but P... |
4,931,558 | 7,469,154 | LINK : fatal error LNK1104: cannot open file 'libcpmt.lib' | I'm setting up a CUDA development environment but it is being challenging...
I installed Visual Studio Professional with x64 compiler tools, CUDA SDK and Notebook Dev Drivers, all 64bit. Also I'm using windows 7 Pro 64bit.
When I try to compile anything it gives the error on the title:
LINK : fatal error LNK1104: canno... | Just followed this post http://blog.cuvilib.com/2011/02/24/how-to-run-cuda-in-visual-studio-2010/
|
4,931,751 | 4,931,827 | #include <string> in a header the defines some structs. ERROR: string does not define a type | #ifndef STRCUTS_H
#define STRCUTS_H
#include <string>
struct menuEntry
{
string itemID; //'string' does not name a type
string itemName; //'string' does not name a type
};
#endif
I get the same error when I put #include < string> above the header guard. Come to think of it, I've had weird trouble with ... | You need to change string to std::string, i.e.
#ifndef STRCUTS_H
#define STRCUTS_H
#include <string>
struct menuEntry
{
std::string itemID;
std::string itemName;
};
#endif
|
4,931,774 | 4,931,917 | Getting a proper value from RegQueryValueEx | I am trying to extract a value from the windows registry of type REG_SZ, using RegQueryValueEx, I got the value except it was riddled with strange "\000" before each letter.To show you what I mean here are some images:
Value I want(It is a device name of a wireless adapter)
Value I got:
here is the code:
HKEY hli... | Since you are using WCHAR, I assume you are compiling with Unicode support. If this is true, then also the buffer needs to be WCHAR.
|
4,931,780 | 4,931,806 | How to nicely "cast" qint64 to int for QProgressBar | I'm playing around with QFtp (yes .. I know) and all works well.
Using code from their own example(s) as a guideline.
http://doc.qt.io/archives/qt-4.7/network-qftp-ftpwindow-cpp.html
The only problem I'm having is when sending (or receiving) big files (let's say 3 GB) the progress bar glitches out.
This is due to the c... | You can make the progress bar present the progress as a percentage:
void FtpWindow::updateDataTransferProgress(qint64 readBytes,
qint64 totalBytes)
{
progressDialog->setMaximum(100);
progressDialog->setValue((qint)((readBytes * 100) / totalBytes));
}
|
4,931,867 | 4,931,907 | throw without arguments for failure signalling | Is it ok to just call throw; from constructor if something goes awry, and you have no idea how to recover?
The idea is to let the app crash with a dump, as the state is unknown. Or should you always specify an argument?
From MSDN I only found that it rethrows if there is no argument, but no idea what happens if there i... | If there's no exception currently being processed throw; will lead to terminate() being called immediately and that will end your program abnormally. That is not very convenient - you'll have less information about what happened compared to throwing a meaningful exception. You could have thrown a meaningful exception, ... |
4,932,208 | 4,932,380 | boost::variant recursive trouble | is there any way to make this work? I hope you'll get the idea, I'm trying to create a list by means of recursive pairs
#include <boost/variant.hpp>
#include <utility>
struct nil {};
typedef boost::make_recursive_variant<nil, std::pair<int, boost::recursive_variant_ >>::type list_t;
int main() {
list_t list = { 1, ... | No. The point of a boost::variant is that it has a fixed size, and does not do dynamic allocation. In this way it's similar to a union. A recursive boost::variant would have to have infinite size in order to contain its largest possible value - clearly impossible.
You could, however, do this by passing it through a poi... |
4,932,520 | 4,932,635 | Get type name as string in Visual Studio 2010 | How can I get the type name of a supplied type as string with C++ using Visual Studio 2010?
Example:
class MyClass { ... };
std::string typestr;
typestr = typeof( MyClass );
//typestr should hold "MyClass" now
| typeid(type).name();
//Or
typeid(expression).name();
Will return type name. This feature is "implementation defined" and standard doesn't saying what exacly name function must return, however in VC++ it is returning what you need (note, that in g++ name function have different behavior).
For more information see thi... |
4,932,667 | 4,933,813 | Windows Forms Designer Custom Control from Label has wrong property value -> designer exception | I'm actually a bit confused here, I've built a dll with a custom control based on Label with AutoSize fixed as true. I happily used it but the designer created the control with AutoSize still set to true.
I changed the dll in an attempt to get the designer to show my control with AutoSize set false and ended up with a... | void set(bool x) override
{
this->AutoSize = false;
}
That's a bug, you call the setter again. This will crash the designer with a stack overflow as soon as you put the control on a form. Fix:
void set(bool x) override
{
__super::AutoSize = false;
}
You must also apply the at... |
4,932,781 | 4,932,879 | Why is a POD in a struct zero-initialized by an implicit constructor when creating an object in the heap or a temporary object in the stack? | The standard and the C++ book say that the default constructor for class type members is called by the implicit generated default constructor, but built-in types are not initialized. However, in this test program I get unexpected results when allocating an object in the heap or when using a temporary object:
#include<i... | It's expected behaviour. There are two concepts, "default initialization" and "value initialization". If you don't mention any initializer, the object is "default initialized", while if you do mention it, even as () for default constructor, the object is "value initialized". When constructor is defined, both cases call... |
4,932,941 | 4,932,998 | Need to extract last figure after dot in a string like "7.8.9.1.5.1.100" | I need to extract last number after last dot in a C++ string like "7.8.9.1.5.1.100" and store it in an integer??
Added:
This string could also be "7.8.9.1.5.1.1" or "7.8.9.1.5.1.0".
I would also like to validate that that its is exactly "7.8.9.1.5.1" before last dot.
| std::string has a rfind() method; that will give you the last . From there it's a simple substr() to get the string "100".
|
4,932,976 | 4,933,431 | Binding Array value in to listview control in nokia Qt? | In my application i have to bind a list of array value in to list view control.
so, I created like this and build successfully but it crash.
QString array_List[5]={"Delphi","Mobile","Dot Net","Java","Open Source"};
for(int i=0;i<5;i++)
{
list << array_List[i];
}
ui->list_View->setMo... | The problem is your are going out of your array.
Replace
i<=5
with
i<5
I would prefer writing:
QStringList list;
list << "Delphi" << "Mobile" << "Dot Net" << "Java" << "Open Source";
ui->list_View->setModel(new QStringListModel(list));
|
4,933,008 | 4,933,043 | Storing Datatype Information | Let's say I have a few variables of different types.
int MyInteger;
double MyDouble;
char MyChar;
Pointers to these variables are stored in a single array of void pointers.
void* IntegerPointer = &MyInteger;
void* DoublePointer = &MyDouble;
void* CharPointer = &MyChar;
void* PointerArray[] = {IntegerPointer, DoublePo... | I suggest you use a variant type. I hate to say it, but try boost::variant (or something similar). Forget all this parallel array and void pointer stuff; a single array of variants achieves the same thing and is more elegant.
|
4,933,219 | 4,933,382 | Convert SID to String | I'm not a C++ developer, so I guess it's just my fault that my program doesn't work.
I want to look up the SID for a windows group and return a readable SID.
wchar_t* SpcLookupName(LPCTSTR lpszSystemName, LPCTSTR lpszAccountName) {
PSID Sid;
DWORD cbReferencedDomainName, cbSid;
LPTSTR ReferencedDo... | There are a couple of obvious things wrong with your code...
1) the prototype for ConvertSidToStringSid() is BOOL ConvertSidToStringSid(PSID Sid, LPTSTR *StringSid); which means that your typedef should be typedef BOOL (WINAPI *tConvertSidToStringSid)(PSID,LPTSTR *);
2) you are looking up the ANSI version and passing a... |
4,933,457 | 4,933,507 | How are you supposed to read the following documentation? | From IDispatch::GetTypeInfoCount
The return value obtained from the
returned HRESULT is one of the
following: [S_OK -> Success],
[E_NOTIMPL -> Failure]
And the sample at the bottom returns E_INVALIDARG and NOERROR.
As far as I see E_INVALIDARG is not S_OK, nor is it NOERROR, so what do you do? Do you check for ... | With COM, you should never check for specific return values unless you actually need to have special handling for those values. Instead, you should use the FAILED or SUCCEEDED macros when you just need to know if a call failed or succeeded. i.e.
HRESULT hr = ...;
if (FAILED(hr)) {
...
COM calls can often return a m... |
4,933,610 | 4,933,740 | boost::asio async_read guarantee all bytes are read | I have a server that receives a compressed string (compressed with zlib) from a client, and I was using async_receive from the boost::asio library to receive this string, it turns out however that there is no guarantee that all bytes will be received, so I now have to change it to async_read. The problem I face is tha... | How were you expecting to do this using any other method?
There are a few general methods to sending data of variable sizes in an async manor:
By message - meaning that you have a header that defines the length of the expected message followed by a body which contains data of the specified length.
By stream - meaning ... |
4,933,662 | 4,933,796 | How to convert GDI+ Status to string? | Actually, the subject. I haven't found any standard way to convert GDI+ Status (error status returned by GDI+ methods) to string, something like FormatMessage()
| If you want to convert labels in GDI+ Status into string, then the simplest thing you can do is this:
const char* StatusMsgMap[] =
{
"Ok", //StatusMsgMap[Ok] = "Ok";
"GenericError", //StatusMsgMap[GenericError] = "GenericError";
"InvalidParameter", //StatusMsgMap[InvalidParameter] = "Inva... |
4,933,789 | 4,933,885 | C++ return type qualifiers heaven | It's hell actually. Can someone please explain in plain English why the below segments work or not?
class Hey;
class Bitmap {
public:
const Hey* const& getHey() { return hey; }; // works
const Hey* & getHey2() { return hey; }; // error C2440: 'return' : cannot convert from 'Hey *' to 'const Hey *&'
private:
... | You can't add const to a pointer more than one type deep which is not itself const, because then you could stuff the address of a const variable into a non-const pointer. Consider:
char c;
char* p = &c;
const char* cp = p; // ok, only one type deep
const char x;
cp = &x; // ok
const char*& r = p; // fail, because...
r... |
4,933,872 | 4,934,002 | Matrix generation in C++ | I have the following code:
for (int w=0; w<10; w++)
{
//some lines of code
unsigned long num = x.to_ulong();
cout << "Decimal form is: " << num << endl;
}
Now what I want is, to make a matrix which will have these values of num, column wise. For example, matrix[i][j], where i is from, let's say "0 to 15... | Here is some pseudo code..
std::vector<std::vector<unsigned long> > matrix(15); // 15 rows
typedef std::vector<std::vector<unsigned long> >::iterator it_type;
it_type row = matrix.begin();
for (int w=0;w<10;w++)
{
//some lines of code
unsigned long num = x.to_ulong();
cout <<"Decimal form is: " << num<< end;
... |
4,933,984 | 4,934,235 | Implementing licensing checking library | I am working on a small cross platform product for Windows and Mac written in C++/Obj-C. I have been asked to implement a licensing module for the same. This task is part of a very ambitious project to introduce licensing for all our products. At the end of it, we will have a complete licensing scheme where we will be ... | I use a system of Partial Key Verification (PKV), and I've implemented this in C# with a PHP generator. Google will come up with various hits, explanations, and implementations; but Brandon Staggs wrote a good overview (albeit in Delphi!), here:
http://www.brandonstaggs.com/2007/07/26/implementing-a-partial-serial-numb... |
4,934,074 | 4,935,130 | How do you play or record audio (to .WAV) on Linux in C++? |
Hello, I've been looking for a way to play and record audio on a Linux (preferably Ubuntu) system. I'm currently working on a front-end to a voice recognition toolkit that'll automate a few steps required to adapt a voice model for PocketSphinx and Julius.
Suggestions of alternative means of audio input/output are w... | The "Hello World" application in the GStreamer documentation shows how to play an Ogg/Vorbis file. To make this work with WAV files, you can simply replace "oggdemux" with "wavparse" and replace "vorbisdec" with "identity" (the identity plugin does nothing -- it's just a placeholder).
To install development support fo... |
4,934,159 | 5,019,425 | SDL_BlitSurface Segmentation fault | I'm getting a segmentation fault from SDL_BlitSurface in C++.
here's the code
mainScreen->draw( 0, 0, background, NULL );
(where mainScreen is an instance of the Screen class) and the draw function of the Screen class is implemented as
void Screen::draw( float x, float y, Texture* source, SDL_Rect* clip)
{
SDL_Rec... | Don't do this:
SDL_FreeSurface( optimizedImage );
You aren't done with the surface (it gets assigned to myimage).
|
4,934,217 | 4,934,267 | Magic numbers in C++ implementation of Excel NORMDIST function | Whilst looking for a C++ implementation of Excel's NORMDIST (cumulative)
function I found this on a website:
static double normdist(double x, double mean, double standard_dev)
{
double res;
double x=(x - mean) / standard_dev;
if (x == 0)
{
res=0.5;
}
else
{
double oor2pi = 1/... | Check out Numerical Recipes, chapter 6.2.2. The approximation is standard. Recall that
NormCdf(x) = 0.5 * (1 + erf(x / sqrt(2)))
erf(x) = 2 / (sqrt(pi)) integral(e^(-t^2) dt, t = 0..x)
and write erf as
1 - erf x ~= t * exp(-x^2 + P(t))
for positive x, where
t = 2 / (2 + x)
and since t is between 0 and 1, you can fi... |
4,934,246 | 4,935,607 | Register class type with numeric identifier | I've got an entity class, a base component class and a few base component derived ones. The entity class contains an array of base component pointers:
class CComponent
{
public:
static unsigned GetType() { return -1; }; //Base identifier
//...
};
class CPoint : CComponent
{
public:
static unsigned GetType(... | Well I know of some ways to achieve the sort of thing you want :
with gcc you can use the non standard typeof(some_type) function which gives you the type to dynamically cast your type. See here.
with C++0x there is a standard way that mimics typeof : decltype(some_type)
you can use the standard typeid that gives you ... |
4,934,635 | 4,934,771 | How can one avoid issues using non-primitive static class variables in c++? | I've read quite a bit about initialization of static class variables in c++ and while the google coding standard says only create statics of plain old data (i.e., primitives & pointers), I see quite a few examples online and in books where the authors violate that guideline.
I've also read that as long as you keep the ... | //impl file snippet
const TheStruct TheClass::Dude = { "Dude", "Dude", 0 };
const TheStruct TheClass::Blah = { "Blah", "Blah", 0 };
const TheStruct TheClass::TheStructArray[] = {TheClass::Dude, TheClass::Blah};
As long as these three lines are written in that order, there is no problem with your code, as they're initi... |
4,934,737 | 4,934,757 | When is the constructor called? | In which of the following is the constructor of myClass called?
1. myClass class1;
2. myClass* class1;
3. myClass* class1 = new myClass;
Thanks a lot
|
Yes - default constructor, instance created on stack
No
Yes - default constructor, instance created on heap
|
4,934,750 | 4,934,803 | Is this a valid datastructure Map<string, string, string> in C++? | I have to store 3 strings per variable, but don't know which is the best data structure to use for that in C++.
I can think of only Struct, but not sure if it is the best way to do it.
Something like string var[100][3], first dimension(100) should be dynamically add and remove.
I tried all sorts of things with map, mu... | If you have always exactly 3 strings together in a triplet and want to have multiple triplets, then define struct with three strings and put it to std::vector.
struct Triplet {
std::string a,b,c;
};
std::vector<Triplet> data;
|
4,934,784 | 4,934,861 | C/C++ enum and char * array | Ran accross the following code in an article and didn't think it was standard C/C++ syntax for the char* array. As a test, both Visual C++ (visual studio 2005) and C++ Builder Rad XE both reject the 2nd line.
Without using #defines, anyone have any tricks/tips for keeping enums and a string array sort of in sync witho... | These are C99 designated initializers. GCC supports them in C90 mode (and in C++) as an extension. Read about it here:
http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html#Designated-Inits
There is no good way to keep enums und strings in sync. If I'd really need this, then I'd write a script to grab the enums decla... |
4,934,926 | 4,935,090 | What does the compiler optimization "constant propagation" mean? | From Effective C++ by Scott Meyers:
template<typename T, std::size_t n>
class SquareMatrix: private SquareMatrixBase<T> {
public:
SquareMatrix( )
: SquareMatrixBase<T>(n, 0),
pData(new T[n*n])
{
this->setDataPtr(pData.get());
}
...
private:
boost::scoped_array<T> pD... | Constant Propagation is a very simple (in the principle) optimization left to compilers.
size_t radius = 5;
size_t diameter = 2*radius;
float perimeter = diameter * 3.1416f;
This will be reduce by the compiler by propagating the constants:
notice that the value of radius is known
execute the computation of 2*radius (... |
4,934,947 | 4,935,432 | Linux fork/exec to application in same directory | Is there an exec variant that will use the current application directory to locate the target program?
I am using C++ and Qt to implement a "last ditch" error reporting system. Using Google Breakpad, I can create a minidump and direct execution to a handler. Because my application is in an unstable state, I just want t... | What you asked for is actually quite easy:
{
pid_t pid = fork();
if (pid == 0)
{
const char* error_reporter_path = "./error_reporter";
execl(error_reporter_path,
error_reporter_path,
(char *) 0);
_exit(127);
}
else
return pid != -1;
}
but it doesn't do what you want. The ... |
4,934,957 | 4,935,474 | Another question on thread safe ref counting | There are tons of questions on how to implement thread safe reference counters.
And a common highly voted answer is: "use atomic increment/decrements".
Ok, this is a good way to read and write refCounter whitout other thread changing it in between. But.
My code is:
void String::Release()
{
if ( 0 == AtomicDecremen... | Your example sounds right to me.
However, the issue here is not about atomic operations, but manually deleting an object and then referencing a soon-to-be-deleted object. What if the reference count, instead of being 1, is 8?.
You need to avoid deleting and invalidating the object manually, and better use some smart po... |
4,934,963 | 4,935,311 | Porting C++ struct to Delphi | First, let me show you the struct:
struct HPOLY
{
HPOLY() : m_nWorldIndex(0xFFFFFFFF), m_nPolyIndex(0xFFFFFFFF) {}
HPOLY(__int32 nWorldIndex, __int32 nPolyIndex) : m_nWorldIndex(nWorldIndex), m_nPolyIndex(nPolyIndex) {}
HPOLY(const HPOLY& hPoly) : m_nWorldIndex(hPoly.m_nWorldIndex), m_nPolyIndex(hPoly.m_nPolyI... | The repetition of HPOLY inside the struct are definitions of constructors for that type. In Delphi, the copy constructor (the third one in the C++, which constructs an instance of this type based on another instance of the same type) not necessary in Delphi. The two-argument constructor lets you specify initial values ... |
4,934,995 | 4,935,023 | Correct way to write file location | What is the correct way to include files
#include "../myDirecoty/myFile.h"
or
#include "..\myDirecoty\myFile.h"
the difference is the direction of "/" or "\".
| This is the correct way:
#include "../myDirecoty/myFile.h"
|
4,935,017 | 4,935,039 | STL performance O(ln(n)) questions | Please, can someone explaine this:
If documentations says that STL std::vector finding element speed performace = O(ln(n)),
what does it mean.
O(ln(n)) - what is "O", where I can read about that?
And where I can read about performace of other STL containers preformance
Thank you very much
| Big O notation is a way to measure how an algorithm will scale as the size of the data on which it is working grows.
Finding an element if a vector is usually O(n), it's only O(lg(n)) when the vector is sorted and you use one of the binary search family of algorithms.
The complexity of each algorithm is specified in th... |
4,935,127 | 4,935,250 | Create a c++ library without a class name | I'm trying to create a C++ dynamic library that won't have a class. I'd like it to work similar to how you can include <string.h> and call strlen directly.
I can create a class that will compile, but won't link correctly with my library.
Here's the test library I'm working on now:
Header
#ifndef _DLL_H_
#define _DLL_H... | extern "C" __declspec(dllexport) int testMethod(int a);
This needs to be dllimport in the application which is linking against the DLL. Most people compile their DLL with a #define which controls if it is an export or an import.
#ifdef INSIDE_MYDLL
#define MYDLLAPI __declspec(dllexport)
#else
#define MYDLLAPI __declsp... |
4,935,203 | 5,018,867 | Looping through the samples of CAF file | Could anyone give me a suggestion or an example of how I would loop through the samples of CAF (Core Audio Format) file? Like taking the first 1000 samples and changing them to 0?
Something like:
for(int i=0; i < numberOfSamples; i++)
{
cafFile.sample[i] = methodThatUsesSampleValue(cafFile.sample[i]);
}
Keep in mi... | Recently I stumbled over the amazing OpenFrameWorks library: http://www.openframeworks.cc/about And I know it compiles on MacOS and iPhone. Amongst many(!) other libs it come with an interface to rtAudio: http://www.music.mcgill.ca/~gary/rtaudio/index.html. You might want to consider also using that directly. Hope that... |
4,935,281 | 4,935,350 | Go to Definition Fails - Visual Studio 2008 | I'm writing a C++ application in Visual Studio 2008. It has a lot of defined structures in several header files, such as:
#pragma pack( push , 1 ) // align on a 1-byte boundary
typedef struct myStruct_tag
{
/* ... */
} myStruct_t;
#pragma pack( pop ) // end 1-byte boundary alig... | Try closing your solution and then deleting the *.sdf file. When you reopen your solution Intellisense will be forced to rebuild its database and this might solve your problem.
Edit: Fixed mistake pointed
Edit 2: For legacy, in case you're using Visual Studio 2008 or older, you should delete all *.ncb files.
|
4,935,709 | 5,505,809 | Advice on organizing sources and builds in C++ development under Linux (CMake as generator) | Can someone propose some good practices for organizing your source files and managing builds when using C++ under Linux. I use CMake to manage my builds although i do not use complex constructs at this point of time.
Let us say we have the following three scenarios.
1. For a makefile application to simply build a few e... | Since you are using CMake I would suggest using out of source builds (Either completely outside or in a build subdirectory of the project root directory) When using more than one configuration and/or compiler at the same time you can create a separate build directory for each one.
In the CMakeLists.txt in the project r... |
4,935,753 | 5,020,711 | How to put global functions which access non-global classes all in one place? | I might not even be posing the question correctly, but here's my situation. I have a namespace into which I want to put all of my global functions. I want to define them all in the corresponding .cpp file. Many of these functions access instances of non-global classes, which may or may not be themselves members of t... | I can't mark a comment as the answer, so I'll just post it myself--basically Oli Charnesworth was right, refactoring was the solution. There was a particular class which was causing my circular dependencies problem, and I just redid things so that it no longer depended on the 'global' info, rather the 'global' info #i... |
4,935,862 | 4,935,942 | VisualC++ function problems (and other) | I have programmed in C++ a while, and I thought It would be fun to try to start with Visual C++ and make a calculator.
Okay, so I have designed at simple window, with two Textboxes, and one button that Adds the two boxes together.
I do know that I dont need a function for this, but I like to try things out, to learn th... | I'm assumming that string a && b are both string values. So you should do something like
if(a.empty() || b.empty())
std::cout << "Values don't exist in one of the boxes" << std::endl;
And the addFunction identifier not found means that the compiler cannot find the addFunction function. Did you declare it? Is i... |
4,936,037 | 4,936,679 | Which audio file format is easiest to manipulate? | Hello nice computer persons,
Per to a question I had earlier concerning accessing the samples in an audio file, I now realize that the Core Audio Format may not be the way to go.
Especially since on page 15 of the spec it mentions something about the use of C being a 'notational convenience' i.e. you can't just crack ... | Uncompressed WAV is the defacto standard for audio editing. You can use various libraries to manipulate them easily. If you simply want completely raw samples without even the WAV header go with PCM however you will have to know your sample rate, frequency, etc ahead of time as you won't have that info that would norma... |
4,936,157 | 4,957,711 | Windows Form Designer thrown exception after changing Custom Control dll | After I have changed my dll containing my custom control I am getting warnings from the build
1>------ Rebuild All started: Project: Easy Labels, Configuration: Debug Win32 ------
1>C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.Targets(1360,9): warning MSB3245: Could not resolve this reference. Could n... | If there is a toolbox item which is an old version, deleting it, closing and re-opening the solution sorts it out.
|
4,936,289 | 4,936,398 | Is volatile a proper way to make a single byte atomic in C/C++? | I know that volatile does not enforce atomicity on int for example, but does it if you access a single byte? The semantics require that writes and reads are always from memory if I remember correctly.
Or in other words: Do CPUs read and write bytes always atomically?
| Not only does the standard not say anything about atomicity, but you are likely even asking the wrong question.
CPUs typically read and write single bytes atomically. The problem comes because when you have multiple cores, not all cores will see the byte as having been written at the same time. In fact, it might be qui... |
4,936,379 | 4,936,428 | How can such code return such mess? | So for more than 10000 openCV images I want to perform something like
int maxVal;
int minVal;
int wh = w*h;
int values[1000];
for(x=0;x<w;x++){
for(y=0;y<h;y++){
double RealColor = cvGetReal2D(source, y, x);
... | This is the result of division by 0, which means that diff is 0, which means some of your images are "flat", so that minVal == maxVal.
|
4,936,497 | 4,936,651 | cin.get in a while loop | I'm trying to get input from user and give output until s/he presses 'n'. It doesn't seem to work. Is problem in scanf or cin.get? When I press y it just takes "tekrar" as an input, thus gives "y" as output and goes into a loop. Also, doesn't stop when i give n as tekrar input.
char cevap[300]="";
char tekrar='y';
whil... | Mixing the various input methods on istream (get, getline, operator>>) can be fraught with peril if you're not aware of which methods leave the delimiter character in the stream and which don't, and handle them accordingly.
In this case, get will read 300 characters of input or input up until the newline, whichever hap... |
4,936,987 | 4,938,266 | C++ class member variable knowing its own offset | Is it possible to have a member variable, that would be able to calculate pointer to the containing object from pointer to itself (in it's method)?
Let's have a foreign call interface wrapped in API like this:
template <typename Class, MethodId Id, typename Signature>
class MethodProxy;
template <typename Class, Metho... | Asking a question is the best way to realize the answer, so this is where I've got:
The offset can't be a template argument, because the type has to be known before the offset can be calculated. So it has to be returned by a function of the argument. Let's add a tag type (dummy struct) and either a put an overloaded fu... |
4,937,012 | 4,937,044 | Why is there a macro which defines _tmain? | I am new to C++ coding, coming from Java and C# background. I'm puzzled by the proliferation of #define terms starting with the most basic:
#define _tmain wmain
When I first learned a smattering of C ages ago, the main function was:
int main(int argc, char *argv[])
In the Visual C++ project I created, it made the mai... | This is a Visual C++-specific feature, it's not a part of C++.
Most of the Windows API functions have two versions: those that end in W, which are for use with wide character strings (wchar_t strings) and those that end in A, which are for use with narrow character strings (char strings). The actual Windows API "fu... |
4,937,136 | 4,937,259 | Boost function and boost lambda | I've seen a few related questions, but am still just puzzled. What's wrong with this syntax:
boost::function<int (int)> g = f;
boost::function<int (int)> g2 = 2*g(boost::lambda::_1);
I've tried it with boost 1.35 and 1.38 (these are the two installations I have lying around) on gcc 4.3.4, and they both give variation... | You can't call a function with a placeholder directly. You have to use bind.
boost::function<int (int)> g2 = 2 * boost::lambda::bind(g, boost::lambda::_1);
(Example)
|
4,937,180 | 4,937,234 | A Base Class pointer can point to a derived class object. Why is the vice-versa not true? | A Base Class pointer can point to a derived class object. Why is the vice-versa not true without casting?
Logically a base class would not have enough information of the derived class but a derived class should have the information of the base class as well.
I am missing some basics here.
| If I tell you I have a dog, you can safely assume that I have a pet.
If I tell you I have a pet, you don't know if that animal is a dog, it could be a cat or maybe even a giraffe. Without knowing some extra information you can't safely assume I have a dog.
similarly a derived object is a base class object (as it's a su... |
4,937,263 | 4,938,331 | Object-oriented networking | I've written a number of networking systems and have a good idea of how networking works. However I always end up having a packet receive function which is a giant switch statement. This is beginning to get to me. I'd far rather a nice elegant object-oriented way to handle receiving packets but every time I try to c... | About the way to handle the packet type: for me the map is the best. However I'd use a plain array (or a vector) instead of a map. It would make access time constant if you enumerate your packet types sequentially from 0.
As to the class structure. There are libraries that already do this job: Available Game network pr... |
4,937,410 | 4,937,515 | converting a byte array into a in_addr or in6_addr and endianness | I'm concerned about endianness when it comes to this problem. Maybe I am overthinking what I have to worry about.
The input to my code is a packet that looks like:
I've received a network packet that contains some bytes. If I know the index in the byte array (and have valid data) of where the in_addr is, is it safe t... | struct in_addr is supposed to be in network byte order, IIRC. Assuming your packet is also delivered in network byte order, you're good to go.
|
4,937,454 | 4,937,471 | What's the correct term for the '...' token? | Consider printf:
int printf ( const char * format, ... );
What are the terms used to describe the ... and the functions that use it? I've been calling it an ellipsis, but that's like calling & the "ampersand operator."
| Variable length parameter list
Edit:
Or, if describing the function itself: Variadic function
|
4,937,475 | 4,938,730 | Deserialize object with references and no default constructor (boost::serialization) | Is it possible in boost::serialization library to deserialize (polymorphic) objects with references and no default constructor?
class Example
{
int& value;
public:
Example(int _value): value(_value) {}
virtual ~Example() {}
friend class boost::serialization::access;
template<typename Archive>
... | As for non-default constructible object, I'd recommend to look the item
Non-Default Constructors
here.
Your class can be serialized by
writing your own function template load_construct_data and save_construct_data.
|
4,937,723 | 4,937,885 | Compiling boost with zlib | I'm compiling boost with bjam under Windows 7 (64bit-should be irrelevant)
D:\development\boost\boost_1_44\libs\iostreams\build>bjam stage ^
--toolset=msvc-10.0 link=static ^
--build-type=complete ^
-s ZLIB_SOURCE=C:\zlib125-dll ^
-s ZLIB_LIBPATH=C:\zlib125-dll\lib ^
-s ZLIB_INCLUDE=C:\zlib125-dll\include ^
-s ZLIB_BIN... | It took me a while to get Boost to build correctly with zlib support.
The problem I ran into was that at some point zlib no longer included a gzio.c source file. The jamfile for the Boost build system (jamfile.v2) had a reference to the gzio module which caused it fail. The solution was to remove that reference before ... |
4,937,741 | 4,937,804 | A Question About Looping | while(thingA is true)
{
}
if(thingA is not true)
{
make thingA true
then back to looping
}
My question is if the looping is true it will keep looping but if it's not I will go through aonther code to make it true, after that I want it to loop again. Can I do that!?
| The code block you have provided is effectively an infinite loop. The reason is because thingA remains true through the while loop, until it evaluates to false and breaks out of the loop. Then it is checked by an if statement that checks to see if it is false - it has to be, or the while loop would not have been brok... |
4,937,846 | 4,937,867 | Can we have a body for the default constructor in C++? | Can we have a body for the default constructor in C++?
Thanks.
| Yes, of course you can. Any constructor that doesn't require an argument is a default constructor.
|
4,937,945 | 4,938,330 | How do I compile my own C++ library for Android? | I have written and tested a library in C++. The code even works in my Android application if I add the source files directly. While I do have experience compiling static and dynamic libraries for common operating systems, I have zero experience compiling for a mobile system like this. I've done some research, and I'm s... | Create a dummy java file with empty code and make sure there is a android_main function in your C++ code. Build using ndk-build. the resulting apk will make your library an application.
See the samples from the android-ndk-r5/samples directory, see the sample native-bitmap to get some idea.
|
4,938,113 | 4,938,211 | C++ templates, efficient function for loading points | I would like to implement a function loading 1D/2D/3D points from file... The template parameter Point can be a 1D 2D 3D point.
template <typename Point>
void List <Point> ::load ( const char *file)
{
...
for ( unsigned int i = 0; i < file.size(); i++ )
{
if ( ... | I think I see what your problem is: you're trying to instantiate this function with a Point class which has (only) a 1-parameter constructor, OR a Point class with a 2-parameter constructor, OR a Point class with a 3-parameter constructor. In either case, you get a compiler error about the number of parameters.
In fac... |
4,938,258 | 4,938,357 | Where can I find good, solid documentation for the C++0x synchronization primitives? | I've seen articles on ::std::thread and ::std::forward and such, but I have seen no good articles on ::std::atomic. There is, of course, the standards proposal paper, but I haven't seen any good documentation for someone who just wanted to use the facility.
Is there any? Where can I find it?
| The just::thread library has decent documentation and was developed by Anthony Williams, author of C++ Concurrency in Action and maintainer of the Boost thread library.
|
4,938,440 | 4,938,748 | C++0x decltype fails to deduce member variable constness | Consider the following code:
template <typename T>
class B
{
};
template <typename T>
B<T> f(T& t)
{
return B<T>();
}
class A
{
class C {};
C c;
public:
A() {}
decltype(f(c)) get_c() const { return f(c); }
};
int main()
{
A a;
a.get_c();
}
When I try to compile this, I get the error:
te... | The compiler operates correctly according to the current C++0x WP. See this issue report, which is currently being worked on.
Possibly the final C++0x Standard won't change the meaning of your decltype application in the return type before the function name. You would need to move it to after the parameter list using -... |
4,938,486 | 4,939,380 | OpenCV & Virsual C++: save Frame data from Camera and then save to Jpg | I am an OpenCV and C++ beginner. I've got a problem with my student project.My Tutor wants to grab frames from a Camera and save the grabbed frames into jpg. So first I used "cvCreateCameraCapture,cvQueryFrame,cvSaveImage" and it worded ok. But the frame is relative big,about 2500x2000,and it takes about 1 second to sa... | If you use C++, why don't you use the C++ opencv interface?
The reason you get N times the same image is that the capture reuses the memory for each frame, if you want to store the frames you need to copy them. Example for the C++ interface:
#include <vector>
#include "cv.h"
#include "highgui.h"
using namespace cv;
i... |
4,938,720 | 4,939,693 | Typecasting from bare data to C++ wrapper | Say I have some data allocated somewhere in my program, like:
some_type a;
and I want to wrap this data in a class for access. Is it valid to say,
class Foo {
private:
some_type _val;
public:
inline void doSomething() { c_doSomething(&_val); }
}
Foo *x = reinterpret_cast<Foo *>(&a);
x->double();
The class h... | 14882/1998/9.2.17:
"A pointer to a PODstruct
object, suitably converted using a reinterpret_cast, points to its initial
member (or if that member is a bitfield,
then to the unit in which it resides) and vice versa. [Note: There
might therefore be unnamed padding within a PODstruct
object, but not at its beginning, as n... |
4,938,875 | 4,940,642 | Do rvalue references to const have any use? | I guess not, but I would like to confirm. Is there any use for const Foo&&, where Foo is a class type?
| They are occasionally useful. The draft C++0x itself uses them in a few places, for example:
template <class T> void ref(const T&&) = delete;
template <class T> void cref(const T&&) = delete;
The above two overloads ensure that the other ref(T&) and cref(const T&) functions do not bind to rvalues (which would otherwi... |
4,938,884 | 4,939,039 | How do I call Poll() with this SOCKET? | SOCKET server = socket(PF_INET,SOCK_STREAM, 0);
bind(server, 7.7.7.7, sizeof(7.7.7.7) );
listen(server, 0);
server.Poll(1, SelectMode.SelectRead);
error C2228: left of '.Poll' must have
class/struct/union type
The IP is not the same but the 3 functions work correctly creating a socket that the server can lis... | Please read this Tutorial.
What you are doing doesn't look close to correct.
|
4,938,935 | 4,939,087 | C++ circular dependency - namespace vs struct | Please educate me. Why does this compile:
struct compiles
{
struct A;
struct B
{
B(const A &a) : member(a.member) { }
int member;
};
struct A
{
A(const B &b) : member(b.member) { }
int member;
};
};
while this does not:
namespace doesnt
{
struct A;
s... | In C++, class scope is special. Any declaration that extends to or past then end of the class definition is automatically extended to the regions defined by its member definitions (3.3.6 [basic.scope.class]).
This means that in the first case both the first declaration of struct A and the full definition of struct A ar... |
4,939,041 | 6,933,288 | How to bring up the on screen keyboard using C++ in Windows 7 tablet devices? | I am developing an application for Windows 7 devices and I'm using an embedded web browser (webkit). Normally touching an edit control on a tablet device causes a little keyboard icon to appear. However, since my edit control is in the browser, it's not a real window with an hwnd and Window's doesn't bring up the ico... | Not sure if you have this answered already. I have been looking at doing a similar thing although it is a part of a larger application and the keyboard is rarely used (but nevertheless had to be supported). I assigned a shortcut key (right click Win 7 on screen keyboard application and choose Properties. In the shortcu... |
4,939,182 | 4,939,247 | When is the 'this' parameter evaluated when calling member functions? | Say I have the following call:
o->f( x, y )
Is o guaranteed to be evaluated before x and y, or is o considered to be an ordinary parameter and thus evaluated at some undefined point along with x and y, before control passes into f?
Basically, are the values of this and c in C::Foo going to be well defined in either Fu... | The postfix expression that selects the function (c->foo or (c++)->foo) and the function arguments are all evaluated before the function is called and there is a sequence point after the evaluation of all parameters and immediately before the function body is entered so you would in theory be guaranteed the side effect... |
4,939,188 | 4,940,024 | Multiple parallel calls to udp::socket::async_receive_from - undefined behaviour? | I am using boost::asio to create a server application, specifically the UDP APIs. Right now I start multiple threads from a pool listening to separate buffers using async_receive_from. This works great on Ubuntu where I develop mostly.
However, when compiling for windows, my callback gets called many times for each sen... | It holds for all the async_xxx functions, you must never call a function on a given socket till the previous one completes - or you'll end up with rubbish (or undefined behaviour)...
EDIT: I work on linux, and I'm surprised that you see it working correctly, as I definitely don't.
EDIT SOME MORE: do it as shown in the ... |
4,939,204 | 4,939,328 | Using an std::string as a key for an std::map | I would like to have an std::map (int .NET 4.0). We of course know that a map is a tree and requires an operator< that string does not define for us.
Error 24 error C2676: binary '<' : 'const std::string' does not define this operator or a conversion to a type acceptable to the predefined operator c:\program files... |
Error 24 error C2676: binary '<' : 'const std::string' does not define this operator or a conversion to a type acceptable to the predefined operator c:\program files\microsoft visual studio 10.0\vc\include\xfunctional 125 1 FXCMMarketDataServer
That's what VC spits into your face when you forgot to include <string>. ... |
4,939,225 | 4,939,899 | Linking with a DLL on Windows Using Maven NAR Plugin | I am trying to build a very simple C++ program using the Maven NAR plugin. I've set up a Maven module for building a shared library, and another for linking in the library and building an executable that uses it. Building on a Mac works great and I can run the program. Unfortunately, building on Windows (XP) with MS Vi... | Answering my own question.
A colleague of mine dug into the murkier recesses of his brain and said he recalled something like "dicklespeck" being needed. That sounded bizarre so I put it in the "if all else fails I'll look that up" bucket. After all else failed, I came back to it and Googled various spellings which rev... |
4,939,496 | 4,939,657 | how to change time in the same line | int main()
{
time_t ltime;
time( <ime );
tm * pTm = localtime(<ime);
while(true)
{
for(int i=0;i<1000;i++)
{
if(i==999)
{
printf("Program time is: %02d:%02d:%02d \r", pTm->tm_hour, pTm->tm_min, pTm->tm_sec);
i=0;
... | you need to refresh pTm each iteration if you want the values to change.
while(true)
{
// get pTm again here.
sprintf(buf, "Program time is: %02d:%02d:%02d\n", pTm->tm_hour, pTm->tm_min, pTm->tm_sec);
}
|
4,939,636 | 4,939,664 | Function to mangle/demangle functions | I have previously, here, been shown that C++ functions aren't easily represented in assembly. Now I am interested in reading them one way or another because Callgrind, part of Valgrind, show them demangled while in assembly they are shown mangled.
So I would like to either mangle the Valgrind function output or demangl... | Use the c++filt command line tool to demangle the name.
|
4,939,691 | 4,939,817 | Opening up TCP Sockets in Java EE Webapplication | We have to communicate with a C++ component from a Java EE web application and my proposal involved using JMS server to communicate with the C++ component which is located on other machine.
However the developer of the C++ component wants me to open up TCP/IP sockets from the webapplication and communicate over XML. My... | Of course it's case by case. But give HTTP a serious chance. It is a good way to cross platform boundaries. It gives you ways to swap out the backend easily and there are many ways to scale it. I've used it from various platforms to hit centralized authentication service written in modern language. I've also done the o... |
4,939,861 | 4,940,002 | Catching a DLL crash in C/C++ | I'm calling a function from a DLL, like this:
__declspec ( dllimport ) bool dll_function(...);
int main() {
[...]
if (dll_function(...)) {
[...]
}
}
In some cases, the data I pass to the DLL function will lead to a crash of the DLL. Is it possible to catch this so my application doesn't crash as well (witho... | You can catch AVs with the __try and __except keywords in the MSVC compiler. Not all that useful, you have no idea what kind of damage was done. The state of your program might well be corrupted. The heap might be blown for example, causing subsequent random failure. Hosting the DLL in its own process and using IPC... |
4,939,921 | 4,939,971 | inline functions returning incorrect results | I have a large application that I am working on in C++, and we have a class where the inline functions are returning the wrong value. It looks like they are offset by one entry.
Here is an example of how the code is set up:
class Test
{
private:
uint myVal1;
uint myVal2;
uint myVal3;
uint myVal4;
... | (I assume that what you posted above is actually a fragment from some header file.)
Things like that typically happen when different source files in your program are compiled with different memory-layout-related settings, like class packing and alignment settings. Your header file is included into these different trans... |
4,940,109 | 4,940,225 | Windows Form Designer Custom Control changes Anchor which works correctly at run-time, but not at design-time | My custom control sets the values I want in the Properties for Anchor on my Custom Label.
With Serializable set to Visible I'm getting the code generated for run-time, which I didn't with type Content, but the control in the designer has the Anchor values a Label is given, (Left and Top), so to get the correct behavio... | You are hardcoding the property value. So assign the value in the constructor, make it non-browsable so it won't show up in the properties window and ensure that the value cannot be changed and doesn't get serialized. Like this:
ref class MyControl : Control {
public:
MyControl() {
__super::Anchor = Ancho... |
4,940,259 | 4,941,046 | lambdas require capturing 'this' to call static member function? | For the following code:
struct B
{
void g()
{
[]() { B::f(); }();
}
static void f();
};
g++ 4.6 gives the error:
test.cpp: In lambda function:
test.cpp:44:21: error: 'this' was not captured for this lambda function
(Interestingly, g++ 4.5 compiles the code fine).
Is this a bug in g++ 4.6,... | I agree, it should compile just fine. For the fix (if you didn't know already), just add the reference capture and it will compile fine on gcc 4.6
struct B
{
void g()
{
[&]() { B::f(); }();
}
static void f() { std::cout << "Hello World" << std::endl; };
};
|
4,940,432 | 4,940,526 | Replace a substring inside a string (c++) | I'm building my own String class
and I want to write my own replace method for the class
However I don't know how to get the position (int) of the first occurrence of substring inside the string.
My replace method should take 2 arguments, String searchString, String newString. It works like this
String example="AppLe";... | Assuming your string class will store the current value in an ASCIIZ buffer, you can use strstr().
|
4,940,453 | 4,966,887 | How to build ACE 6.0(network library) as static? | ACE supplied solution file for Visual Studio, and there were solution files for static and dynamic liking.(ACE.sln and ACE_static.sln)
After they release 6.0, there was no static.sln anymore.
I can't understand. Why did they remove solution file for static? Is there a reason?
I'm putting predefined values for static ... | I've just posted the same question on the comp.soft-sys.ace newsgroup where I got some help from one of the ACE developers:
ACE 6.0 Static Builds
Basically there's a Perl tool called MPC that's distributed with ACE that they use to compile all the build files (I haven't gotten it to work yet but then that's probably ju... |
4,940,547 | 4,940,953 | I'm trying to use this Boost C++ code and I have a problem | First I'll explain, then I'll paste the code. I actually copied the code from this example
http://www.boost.org/doc/libs/1_45_0/libs/graph/example/prim-example.cpp
And then I'm trying to get it to work with an input from a text file, just like I did for the Boost Kruskal algorithm.
Using the debugger, I know that the s... | It should be "edge_array" and not "edges" (that one was part of the original code).
|
4,940,809 | 4,940,850 | How to find a lower bound in a sorted vector | I'm pretty new to C++ and do not understand all the concepts of the STL library, so bear with me.
I wrote the following code snippet (pasted below) to find the lower_bound in a sorted vector.
Although this code works fine in Release mode, it asserts in debug mode (VStudio-8).
I believe this is because less_equal<int> ... | The STL uses strict weak orderings because given a SWE (let's denote it <), you can define all six of the relational operators:
x < y iff x < y
x <= y iff !(y < x)
x == y iff !(x < y || y < x)
x != y iff (x < y || y < x)
x >= y iff !(x < y)
x > y iff y < x
As fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.