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,325,407 | 4,326,024 | How to decide when to implement a C++ template? | I'm coming from C, and getting deeper and deeper into C++. Using the container classes of the standard library, as-well as the smart pointer classes from the boost library, I've had my first introduction to class templates. I use them a lot now.
Recently I made my first approach of writing my own class templates. But 9... | C++ proposes several programming paradigms, as you have discovered, and they are not exclusive.
What you write with templates could generally be written with Object-Oriented codes, so it's usually a matter of trade-off.
The C++ templates follow the Generic Programming paradigm, the idea is that your class / method will... |
4,325,483 | 4,325,906 | How to remove the "default button" border? | When you have a GtkButton in GTK and it is the default for some window (will be activated when you press Enter), a tiny border is draw around it to inform the user that the button is the default button. How to remove this border ?
I already tried: default-border and default-outside-border style properties.
| After hours finding for this, I've discovered it:
gtk_button_set_relief(GTK_BUTTON(button_widget), GTK_RELIEF_HALF);
GTK should have a gallery showing how this changes the button behavior.
|
4,325,802 | 4,325,865 | Changing the linkage of a name | An attempt to change the linkage of a name i is made in this code. Is it legal in C/C++?
static int i = 2;
int i;
int main()
{
return 0;
}
| In C++ your code is ill-formed (you have multiple definitions of variable i) i.e a standard conformant compiler is required to issue an error message
$3.2.1 (C++03)
No translation unit shall contain more than one definition of any variable, function, class type, enumeration type or template.
In C99 your code invokes... |
4,325,849 | 4,325,898 | Functionality of pointers and references | I'm pretty much a beginner at C++. Just started learning it a few weeks ago. I'm really interested in improving my skills as a programmer, and there's something that's been confusing me in the last few days. It is pointers. Pointers and the reference operator. My question is, what exactly is the functionality of the po... | Definitely check this question out, the accepted answer explains pointers and common errors with them in a nice manner.
Update: a few words of my own
Pointers are bunches of bits, like any other kind of variable. We use them so much because they have several very convenient properties:
Their size (in bytes) is fixed, ... |
4,325,947 | 4,325,966 | Free Allocated Memory Generates Exception - C++ | There is a function in my application in which memory is allocated for formatting a port name. CreateFile is called to open the port. At the end of the function free is called to attempt to free the allocated memory.
DWORD CSerialPort::Open( wchar_t * port )
{
DCB dcb = {0};
LPTHREAD_START_ROUTINE pThreadStar... | malloc allocates bytes, but you are using the allocated memory to store wchar_t.
You have to change the malloc size parameter to match your existing memcpy usage:
pwcPortName = (wchar_t *)malloc( wcslen( port ) + 6 );
should be
pwcPortName = (wchar_t *)malloc( (wcslen( port ) + 6) * sizeof(wchar_t));
|
4,326,045 | 4,326,070 | Is new C++ backward compatible | I haven't coded in C++ for years. I recently discovered that during those years it has changed quite dramatically. I'm not sure I like the changes, but that's another discussion.
I still have some C++ code knocking around my hard drive. If I got it out and tried to compile it with a nice new C++ compiler, say the lates... | In general, yes it is backwards compatible. However, the devil is in the details. You likely will find things where conventions change, or specific libraries fall into or out of use.
|
4,326,094 | 4,326,269 | C++ file container (e.g. zip) for easy access | I have a lot of small files I need to ship with an application I build and I want to put this files into an archive to make copying and redistributing more easy.
I also really like the idea of having them all in one place so I need to compare the md5 of one file only in case something goes wrong.
I'm thinking about a c... | The answer depends on whether you plan to modify the archive via code after the archive is initially built.
If you don't need to modify it, you can use TAR - it's a handy and simple format. If you want compression, you can implement tar.gz reader or find some library that does this (I believe there are some available,... |
4,326,176 | 4,326,204 | inheritance and namespaces | I am trying a my first useful object oriented program with some namespace usage.
I have a base class B which is in the namespace NS. If I try to inherit from this
base class to get the inheritance work, I should use the NS::B in the class decleration as below, is this really the case? Or is there a more widely accepte... | If your D is in namespace NS, you don't have to qualify NS::B, since D and B are in the same namespace. You can just use class D : public B.
|
4,326,199 | 4,326,222 | Why is this function segfaulting? | The function is this:
Set::Set(Multinumber* tempArray[], int tempSize)
{
numElements = tempSize;
capacity = tempSize*2;
setArray = new Multinumber*[capacity];
for (int i=0; i<numElements; i++)
{
addElement(tempArray[i]);
}
}
The variable setArray is declared in my header to be of type Multinumber**
It segfault... | carr[1]=c4;
carr[2]=c5;
Shouldn't that be
carr[0]=c4;
carr[1]=c5;
?
Piece of advice: If you load this up in a debugger, such as gdb, it would have identified the culprit line and you would've seen your error very quickly.
|
4,326,315 | 4,334,102 | Apply VST audio effect/plugin to audio-file | This is my first question after leeching over here for some time.. So spare me.
I need to apply the iZotope Vinyl VST effect to some audio files via CLI or C++ (so language doesn't really matter), it has to work on a Mac or on a Unix based system. I've researched all over the webs and can't find any working solution.
I... | I'm the author of MissWatson, and as you probably noticed on the webpage, I unfortunately was required to close-source the code, so I can't really ask you for more diagnostic information, since I wouldn't be able to patch MissWatson if it's a bug there. However, I would recommend running MissWatson with the -verbose s... |
4,326,379 | 4,326,555 | native C++: WSDL proxy generation library | It is necessary to communicate to WebService from C++ MFC application. I can add reference to the service, but wsdl is generated for if simple types are used only. Attempt to generate proxy for methods with complex types returns an error:
does not support extension of complexType
Here is a suggestions to fix that: ht... | Is gsoap what you are looking for? It can generate both client and server sides of a Web Service in C or C++.
|
4,326,414 | 4,326,474 | Set breakpoint in C or C++ code programmatically for gdb on Linux | How can I set a breakpoint in C or C++ code programatically that will work for gdb on Linux?
I.e.:
int main(int argc, char** argv)
{
/* set breakpoint here! */
int a = 3;
a++; /* In gdb> print a; expect result to be 3 */
return 0;
}
| One way is to signal an interrupt:
#include <csignal>
// Generate an interrupt
std::raise(SIGINT);
In C:
#include <signal.h>
raise(SIGINT);
UPDATE: Microsoft Docs says that Windows doesn't really support SIGINT, so if portability is a concern, you're probably better off using SIGABRT.
SIGINT is not supported for an... |
4,326,534 | 4,328,030 | X11/Xlib: Create "GlassPane"-Window | I've tried to create a fully transparent window using C++ & X11. It should not consume any events and simply forwards them to the windows below. Some kind of GlassPane as it's known for Java-Windows, but full screen. Then I'd like to draw on this window.
Is this somehow possible with X11?
My first attempt was ignoring ... | You can create an output-only window by setting its input shape to empty.
The API is XFixesSetWindowShapeRegion() and you can set ShapeInput separately from ShapeBounding. XFixesCreateRegion() is used to get a region to pass in.
Then you need an RGBA (with-alpha-channel) visual so you can draw transparent pixels into m... |
4,326,577 | 4,326,908 | Help with this design issue | I'm making a game GUI API. It is coming along very nicely except for one aspect. I want themes similar to how GTK works. The way I want it to work is that every GUI element will have a default Windows9X-like way of drawing themselves. If it is found that a theme is set for that type of widget, it will be drawn with tho... | May be template the superButton on a policy and then have a default policy which does the default and the user has the option of providing a different policy? The policy could then define the attributes of the button (such as the hover image etc.) - does what I describe make sense?
|
4,326,652 | 4,326,722 | std::unordered_set constructors | I've been looking at the constructors of unordered_set. Is it not possible to construct an unordered_set with a custom allocator instance WITHOUT setting the number of hash buckets? I'd really rather not mess with implementation details because I want a custom allocator, and the type provides no definitions for the def... | That's strange, but you are right. I suppose the thought was that it's overkill to support all possible parameter combinations, with defaults.
The best way I can think to handle this is to construct an empty unordered_set with all default settings, get the default bucket count from it using unordered_set::bucket_count... |
4,326,674 | 4,326,831 | Template type is not "seen" by the compiler inside a lambda | template<typename Wcf, typename Wdb>
void ComputeGenericDropCount(const function<void(Wdb *, int)> &func)
{
Wcf::ForEach([&](Wcf *wcf) {
Wdb *wdb = Wdb::Find(wcf->sourceId); // <--- ERROR
// error C2653: 'Wdb' : is not a class or namespace name
if(wdb)
func(wdb, wcf->itemCo... | Don't know why it doesn't work. But here is a workaround.
template<typename Wcf, typename Wdb>
void ComputeGenericDropCount(const function<void(Wdb *, int)> &func)
{
auto my_find = Wdb::Find; // allows lambda to "capture" the correct function.
Wcf::ForEach([&](Wcf *wcf)
{
Wdb *wdb = my_find(wcf->so... |
4,326,843 | 4,326,930 | VS10 Crashes When Doing “Build” or “Rebuild” of C++ Project | I posted this on programmers first, but was told it belongs here. Funny, I didn't think so.
I have VS10 installed on a Windows Server 2008 R2 box, along with several other versions of VS dating back years. This is our production build machine.
When I load or create any C++ project and do a Rebuild or Clean, the IDE cr... | How about contacting MS support directly? If this is blocking your work, you can push them to have it fixed (don't know about costs though, will probably depend on the product and specificities of your license...).
Alternatively, you can build your solution in the commandline: open a VS 2010 command prompt (shortcut is... |
4,326,864 | 4,326,918 | Ambiguous call to a function | I have four functions:
template<class Exception,class Argument>
void allocate_help(const Argument& arg,Int2Type<true>)const;
template<class Exception,class Argument>
std::nullptr_t allocate_help(const Argument& arg,Int2Type<false>)const;
template<class Exception>
void allocate_help(const Exception& ex,Int2Type... | Because your call matches both:
template<class Exception,class Argument>
void allocate_help(const Argument& arg,Int2Type<true>)const;
with Exception = std::bad_alloc and Argument = std::bad_alloc (Argument is automatically deduced), and:
template<class Exception>
void allocate_help(const Exception& ex,Int2Type<true>... |
4,326,954 | 4,331,594 | WM_DEVICECHANGE Messages Are Not Sent to WndProc - C++ | My application creates a window for the purpose of handling the WM_DEVICECHANGE Windows message. WndProc does get called several times, until my application calls a function to poll for keyboard events, but for whatever reason it does not get called when I remove or insert my USB device.
This is the GUID for my USB de... | You're missing a message pump to retrieve the notifications from the queue and dispatch them to your WndProc. The message pump is effectively a loop that checks for messages and calls the appropriate WndProc synchronously. MSDN has some good information on them. I don't know what the context of your code is, so I'm not... |
4,327,172 | 4,330,872 | Separation of background/foreground layers in a scanned document | I need to automatically remove the mildly colored background of a scanned document image for OCR.
ScanTailor is an open source C++ GUI-based app that does background separation among other things, but I cannot figure out how to run only the last step which actually removes the background.
Ideally, I could find the code... | You are referring to Thresholding, Despeckling and Noise Removal techniques which are necessary in OCR applications.
The quality of the results depends very much an many different factors -
Print quality of the original
Scan quality
Image resolution
Background colours and patterns used.
Noise and other marks.
You may f... |
4,327,220 | 4,327,314 | X-platform reentrant wcstok()? | Right now I'm looking for a reentrant version of wcstok() that is known by GCC and other compilers (if there's any).
So far I use wcstok_s() but that one is MSVC only and I need to compile the code on other platforms as well. While some pages suggest wcstok_r() I couldn't find it in my GCC headers. Other (man)pages men... | The function wcstok specified by C89 (and therefore C++) is reentrant and has the same signature and essentially the same behavior as Microsoft's wcstok_s. wcstok should be declared in <wchar.h> and/or <cwchar>.
wchar_t* wcstok(wchar_t* s, const wchar_t* delim, wchar_t** ptr);
But it looks like Microsoft's wcstok has... |
4,327,278 | 4,327,744 | Is a Boost windows program portable to other windows systems? | I'm considering two options for a program. Either C++ with Boost Asynchronous IO or Java with the asynchronous NIO. I know that Java is portable so long as the system has the java run time. I'd prefer to use C++ with Boost but I'm not sure if the program I write can be ported to a different Windows machine and still ru... | So long as you use Boost, the C++ Standard Library (and the CRT, if you feel you must), your code will port pretty easily.
Make sure you avoid any Microsoft CRT extensions such as the str*_s functions (e.g. here) - MSDN does not flag these very well as nonstandard, unfortunately.
Also avoid using C++0x features in ... |
4,327,384 | 4,327,487 | configuring boost::thread stack size | Is there a way to configure the boost::thread stack size?
| No, AFAIK.
Maybe you could try with native_handle() thread's member function and set the stack size with a call to OS' API (pthread_attr_setstacksize() on POSIX systems maybe?).
|
4,327,399 | 4,327,706 | Extensible parser design | I have a class Target with a "fileType" enum which holds all kinds of files my parser needs to know about (currently SOURCE, HEADER, RESOURCE). I'd like my Parsing function to be able to do something generic like:
if( token == some_known_fileType )
put_nextToken_in_the_list_for_that_fileType();
else
return an_e... | I believe this is not usually the right approach, but that's my belief. I would do this in a different way.
Take a step back and what are we trying to achieve, we want to control the behavior based on an incoming (input parameter) value.
Lets say we have classes: FileA FileB ...
the file_type holds the type of file.
Us... |
4,327,421 | 4,327,571 | Statically linked xerces 3.0.0 does not work while dynamic works on Linux | So I am trying to statically link Xerces 3.0.0 on linux.
I did it already with dynamic link and it works, but in order to avoid dependancy I want to do it statically.
I changed all of the make files to do it in appropriate way
-Wl,-Bstatic ... -lxerces-c -Wl,-Bdynamic ...
But I am getting following errors:
undefined ... | The dynamic version of the xerces will have dependencies on libpthread that ensure the loader will pick up the correct library.
Specifying libphtread on your linker command line should fix those unresolved externals, did you (a) put in in the right place on the command line as the ordering matters and (b) did you try t... |
4,327,474 | 4,354,045 | Does perfect forwarding in C++0x make reference_wrapper deprecated? | As usual, code first:
#include <functional>
using namespace std;
using namespace std::tr1;
void f(int& r) { r++; }
template<class F, class P> void g1(F f, P t) { f(t); }
template<class F, class P> void g2(F f, P&& t) { f(forward<P>(t)); }
int main()
{
int i = 0;
g1(f, ref(i)); // old way, ugly way
g2(f... | Reference wrappers are still useful. This is the case when it's about storing things. For example, with reference wrappers you can make std::make_tuple and std::thread create objects which refer to some argument instead of copying them:
class abstract_job
{
public:
virtual ~abstract_job() {}
virtual void run() ... |
4,327,730 | 4,327,778 | Why is T&& instantiated as int&? | Can anyone please explain why this compiles and why does t end up with type int&?
#include <utility>
void f(int& r)
{
++r;
}
template <typename Fun, typename T>
void g(Fun fun, T&& t)
{
fun(std::forward<T>(t));
}
int main()
{
int i = 0;
g(f, i);
}
I see this on GCC 4.5.0 20100604 and GDB 7.2-60.... | Because of perfect forwarding, when the argument to P&& is an lvalue, then P will be deduced to the argument's type plus having a & attached. So you get int & && with P being int&. If the argument is an rvalue then P will be deduced to only the argument's type, so you would get an int&& argument with P being int if you... |
4,328,342 | 4,328,396 | float bits and strict aliasing | I am trying to extract the bits from a float without invoking undefined behavior. Here is my first attempt:
unsigned foo(float x)
{
unsigned* u = (unsigned*)&x;
return *u;
}
As I understand it, this is not guaranteed to work due to strict aliasing rules, right? Does it work if a take an intermediate step with ... | About the only way to truly avoid any issues is to memcpy.
unsigned int FloatToInt( float f )
{
static_assert( sizeof( float ) == sizeof( unsigned int ), "Sizes must match" );
unsigned int ret;
memcpy( &ret, &f, sizeof( float ) );
return ret;
}
Because you are memcpying a fixed amount the compiler will opt... |
4,328,383 | 5,049,716 | Qt Creator - how to set application icon for ubuntu linux? | I have seen the original question qt-creator-how-to-set-application-icon
but it did not help me because i am building an app in ubuntu and the Qt`s Documentation
is not clear for me..
Is there anynone, who has done it?
Whats the method?
Thanks in advance.
| Linux does not have any standard for reading embedded resources, so there is no way to embed the icon in the application binary itself and have it display in the menu and launcher. You will have to install your icon in the appropriate pixmaps directory and a .desktop file in appropriate apps directory pointing to your ... |
4,328,560 | 4,328,628 | Marshalling double parameters with P/Invoke | I have a problem with a P/Invoke call I'm trying to do. I have to call a C++ class from a C# program. I have the source of this class so what I did is put it in a DLL project and create export functions to access it's main method. That should be enough to do what I need and keep things simple.
My export method looks li... | You should declare your C++ function as __stdcall, which is the P/Invoke default:
extern "C" _declspec(dllexport) void __stdcall Inference(double *c1, double *c2, double *c3, double *result);
It's also possible to leave the C++ prototype alone and change the P/Invoke declaration:
[DllImport("InferenceEngine.dll", Call... |
4,328,768 | 4,328,855 | C++ Threads - pthread_create, pthread_join | Can you tell me what I am doing wrong here? I am implementing pthread_create incorrectly
int iret1 = pthread_create(&producer, NULL, produce, void*);
int iret2 = pthread_create(&consumer1, NULL, consume, void*);
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <ctime>
#include <time.h>
#define EMPT... | If you are not using thread routine argument, just pass NULL pointer instead of void*:
pthread_create( &producer, NULL, produce, NULL );
The thread routine is supposed to be of void* ()( void* ) type. Yours are different. It should be something like:
/// My fancy producer thread routine
extern "C" void* produce( void*... |
4,328,924 | 4,328,997 | Suppress output from base class constructor | I have a series of classes that tells the debug stream (std::cout in this case) that it has been created, allowing me to follow the program execution nicely. I have several classes that are subclasses of base classes which are not abstract, which results in a double message when a subclass instance is created. I would ... | There's no way to suppress the code in the base constructor, unless the code in the base constructor checks some condition itself. You may achieve this by e.g. passing a special flag to the base constructor (having default value NOT prohibiting the debug output).
class Base
{
public:
Base(bool suppressDebugInfo =... |
4,328,955 | 4,329,090 | OpenCV gets aways with assigning to a const reference? | I stumbled upon this piece of code in the openCV source ( cxoperations.hpp, line 1134, in the definition of the Vector class ):
Vector(const Vector& d, const Range& r)
{
if( r == Range::all() )
r = Range(0, d.size());
// some more stuff...
}
Note that the Vector class has no data member called r (and ... | I notice cv's Vector is a class template. So if that class method was never instantiated, there was no compiler error. My guess is that if you try
Vector<int> a;
Vector<int> b(a, Range::all());
you'll get a compiler error on that suspicious-looking line. Then you can report it as a bug in the OpenCV source.
|
4,329,284 | 4,329,309 | C++ Boost random numeric generation problem | I must generate a random number using boost libraries, I use this code:
boost::mt19937 gen;
boost::uniform_int<> dist(kUIMinManPort, kUIMaxManPort);
boost::variate_generator< boost::mt19937&, boost::uniform_int<> >
var(gen, dist);
unsigned int value = (unsigned int)var();
return boost::lexical_cast<std::string>(value);... | static boost::mt19937 gen(static_cast<unsigned int>(std::time(0)));
The static makes sure that the generator is only created once. The problem is that time isn't changing fast enough. If you call your function in the same millisecond, you'll get the exact same results. Unfortunately, your code is just that fast that y... |
4,329,307 | 4,475,954 | using g++, how to deprecate virtual class member functions | I seem to be having trouble getting deprecated warnings to print out, for functions declared as virtual.
I'm using "g++ (GCC) 4.1.1 20061011 (Red Hat 4.1.1-30)."
My research shows that there might be problems in gcc 4.x regarding deprecating
pure virtual functions(i.e. class bueller{ virtual int cameron()=0;};),
but no... | Given this program:
struct Foo
{
virtual void Foo_B() __attribute__((deprecated)); //virtual
};
struct DerivedFoo : public Foo
{
};
int main()
{
DerivedFoo d;
d.Foo_B();
Foo &f = d;
f.Foo_B();
}
void Foo::Foo_B() {}
On CentOS 5.2 (gcc version 4.1.2 20080704 (Red Hat 4.1.2-44)), I get the same output that ... |
4,329,324 | 4,329,352 | C++ error: "Array must be initialized with a brace enclosed initializer" | I am getting the following C++ error:
array must be initialized with a brace enclosed initializer
From this line of C++
int cipher[Array_size][Array_size] = 0;
What is the problem here? What does the error mean? Below is the full code:
string decryption(string todecrypt)
{
int cipher[Array_size][Array_size] = 0;... | The syntax to statically initialize an array uses curly braces, like this:
int array[10] = { 0 };
This will zero-initialize the array.
For multi-dimensional arrays, you need nested curly braces, like this:
int cipher[Array_size][Array_size]= { { 0 } };
Note that Array_size must be a compile-time constant for this to ... |
4,329,419 | 4,329,822 | How to create openCV image of certain (R, G, B) color and get that color name? | I need to create an image filled with some (R,G,B) color. And get that color name like some (R,G,B) = black or red and so on. Can we do such thing with openCV, and how to do it?
| opencv doesn't create images with a color, easiest way is either a fill or just draw a filled rectangle with the chosen color.
See https://docs.opencv.org/trunk/dc/da5/tutorial_py_drawing_functions.html
There isn't (AFAIK) a function to return the color name, easiest way is to get a list of colors from somewhere and ch... |
4,329,463 | 4,329,494 | readability of long int v. long | Which is more clear to someone reading code? "long" or "long int". "long int" is more descriptive, but "long" is more succinct.
| "Long int" is more descriptive, but "long" is more succinct.
|
4,329,677 | 4,330,641 | Increment operator/ iterator implementation | I am trying to figure out a couple of things here:
How do I write an increment operator for a node class that has a pointer to the next node?
How do I implement iterators for a class like below?
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class Node {
public:
Node(int i=0):val... | You don't implement operator++ for the Node class; you implement it for the iterator. The iterator class should be a separate class.
And please, don't spoil your template by making assumptions (since val is a T, your constructor should accept a T, not an int). Also, do not ignore the int parameter to operator++ like th... |
4,329,777 | 4,337,544 | Is `long` guaranteed to be at least 32 bits? | By my reading of the C++ Standard, I have always understood that the sizes of the integral fundamental types in C++ were as follows:
sizeof(char) <= sizeof(short int) <= sizeof(int) <= sizeof(long int)
I deduced this from 3.9.1/2:
There are four signed integer types: “signed char”, “short int”,
“int”, and “long in... | The answer is definitively YES. Read my OP and all the comments to understand why exactly, but here's the short version. If you doubt or question any of this, I encourage you to read the entire thread and all of the comments. Otherwise accept this as true:
The C++ standard includes parts of the C standard, including... |
4,329,835 | 4,329,885 | Whats the difference between ofstream "<<" and Write | I had opened a file in binary mode and like to write to an file .
ofstream ofile("file.txt",ios_base::binary)
int a = 1;
float f = 0.1;
string str = 10;
ofile<<a<<f<<str;
Like to know what the difference between writing using "<<" and using "ofile.write" .
which is the best and effective to write i... | operator<< will format your data as text. Whereas write will output data in the same format as it's stored in ram. So, if you are writing binary files, you want to use write.
However, if you are writing non-pod types, you need to be careful. You can't just say:
write( &mystring, sizeof(std::string) );
You need to h... |
4,329,869 | 4,329,894 | How do you create a hash table in C++? | I am creating a simple hash table in VS 2008 C++.
#include <map>
std::map <string, char> grade_list;
grade_list["John"] = 'B';
I am getting the error:
error C2057: expected constant expression
What does that mean? Does boost library have something better?
Thanks!
| #include <map>
#include <iostream>
#include <string>
int main() {
std::map<std::string, char> grade_list;
grade_list["John"] = 'B';
std::cout << grade_list["John"] << std::endl;
return 0;
}
This works great with g++.
You should specify std:: before string in your map declaration, as I did in my code.
|
4,330,027 | 4,331,086 | Thread Fails to Exit On Application Exit - C++ | My application creates a thread that polls for Windows messages. When it is time to close down, my application sends the WM_QUIT message.
In the application thread, this is how I am attempting to shut things down:
if ( _hNotifyWindowThread != NULL )
{
ASSERT(_pobjNotifyWindow != NULL);
::SendMessage( _pobjNot... | This the complete answer (I'm almost sure):
replace
::SendMessage( _pobjNotifyWindow->m_hWnd, WM_QUIT, 0, 0 );
with
::PostMessage( _pobjNotifyWindow->m_hWnd, WM_CLOSE, 0, 0 );
replace
( (bRetVal = ::GetMessage( &msg, _pobjNotifyWindow->m_hWnd, WM_DEVICECHANGE, WM_DEVICECHANGE )) != 0 )
with ( (bRetVal = ::GetM... |
4,330,616 | 4,330,916 | Memory failures when calling new | It might be a little hard to explain everything about this error but I'll try my best. Unfortunately the code is so large that it would be unpractical to try to include it.
I am writing an academic OS for homework (nachos if you must know) and the most recent thing I needed to do was implement mutual exclusion in a cor... | malloc is just the victim here. In some completely different part of the code you have written outside the allocated boundaries and thus have corrupted chain links that are used by the heap manager to track free/allocated blocks. As you try to allocate here, the heap manager is chasing these linked lists and lands into... |
4,331,098 | 4,331,194 | C++ - Alphabetizing Strings | I am currently reading information from an input file. Of that information, there is a name. All the information is read into a struct. There is an array of these structs.
I need to alphabetize the structs by the last name, using a Binary Search Tree.
Do I need to write an operator overload function for ==, <, and >. I... | Operator overloads work just like functions or methods. They get a return type and arguments in just the same way. For instance, a binary operator (like <) would be a member function with one argument or a free function with two, one each for each side of the operator. the only thing that's different is instead of h... |
4,331,371 | 4,331,509 | Random seed at runtime | How can I generate different random numbers at runtime?
I've tried
srand((unsigned) time(0));
But it seems to get me a random number on every startup of the program, but not on every execution of the function itself...
I'm trying to automate some tests with random numbers, random iterations, number of elements, etc...... | srand()
As others have mentioned. srand() seeds the random number generator. This basically means it sets the start point for the sequence of random numbers. Therefore in a real application you want to call it once (usually the first thing you do in main (just after setting the locale)).
int main()
{
srand(time(0))... |
4,331,599 | 4,337,552 | Calling Python functions from C++ | I am trying to achieve call Python functions from C++. I thought it could be achieved through function pointers, but it does not seem to be possible. I have been using boost.python to accomplish this.
Say there is a function defined in Python:
def callback(arg1, arg2):
#do something
return something
Now I nee... | If it might have any name:
Pass it to a function that takes a boost::python::object.
bp::object pycb; //global variable. could also store it in a map, etc
void register_callback(bp::object cb)
{
pycb = cb;
}
If it is in a single known namespace with a consistent name:
bp::object pycb = bp::scope("namespace").at... |
4,331,717 | 4,331,786 | Minimizing memory usage of a breadth first search | In my the following code, I am traversing a graph through breadth first search. The code constructs the graph while it is traversing. This is a very large graph, with a fan out of 12. Due to this, any time the depth of the breadth first search increases, I want to destruct the layer above it in an attempt to minimize m... | With constant fanout and assuming a tree-like graph, the number of nodes that have been visited by a BFS is almost the same as the number of nodes on the fringe. (e.g. in a tree with fanout K, each level n has K^n nodes, and the number of nodes with lower depth than n is also Theta(K^n)).
Hence, storing the fringe will... |
4,331,837 | 4,332,084 | Why can't functions be overloaded by return type? |
Possible Duplicates:
Function overloading by return type?
Puzzle: Overload a C++ function according to the return value
Because I have a library which exposes a bunch of functions in the form of:
bool GetVal();
double GetVal();
int GetVal();
long GetVal();
//So on.
And now I have to wrap these. I'd rather not rewr... | You can't overload on return types as it is not mandatory to use the return value of the functions in a function call expression.
For example, I can just say
GetVal();
What does the compiler do now?
|
4,331,960 | 4,342,302 | Where is the Makefile generated by the Eclipse CDT? | I've built a hello world C++ project with Eclipse(helios) CDT. It compiled fine. But I would like to take a look at the Makefile CDT generated. I can't find it in project folder/debug/release folders or in the src folders. Where can I find this Makefile?
| If you use the default setttings with current builder = CDT internal builder, there is no make file.
if you select current builder = GNU make, you will see the makefile in the debug folder.
|
4,331,962 | 4,331,991 | '=' AND '!=' operator overloading problem | Okay, my evil compiler keeps rejecting my '=' AND '!=' overloaded operators for (I think) both my Polynomial and Rational classes. Help is greatly appreciated.
using namespace std;
class Polynomial
{
public:
//constructor
Polynomial()
{
for ( int i = 0; i < 100; i++ )
{
coefficient[i] = 0;
... | Try reading the error messages?
binary '=' .... right-hand operand of type 'int' .... while trying to match the argument list '(Rational, int)'
Both operator = implementations that I can see take a Rational& or a Polynomial& but none take an int. That being said there is clearly some information missing from your ques... |
4,332,109 | 4,332,128 | Static and dynamic binding | Do you set an option to tell the compiler to statically or dynamically bind the .lib or how would you check if the .lib is statically binds with .exe?
| Run depends.exe with the /Dependents flag. Here's the output for cl.exe using depends.exe with VS2010 on WinXP.
dumpbin /DEPENDENTS cl.exe
File Type: EXECUTABLE IMAGE
Image has the following dependencies:
ADVAPI32.dll
KERNEL32.dll
MSVCR100.dll
mspdb100.dll
Image has the following delay load dependencies:
VERSION.dll... |
4,332,164 | 4,332,224 | Compiler optimization problem | Most of the functions in <functional> use functors. If I write a struct like this:
struct Test
{
bool operator()
{
//Something
}
//No member variables
};
Is there a perf hit? Would an object of Test be created? Or can the compiler optimize the object away?
| GCC at least can optimize the object creation and inline your functor, so you can expect performance as with hand-crafted loop. Of cource you must compile with -O2.
|
4,332,286 | 4,332,305 | How do I find how C++ compiler implements something except inspecting emitted machine code? | Suppose I crafted a set of classes to abstract something and now I worry whether my C++ compiler will be able to peel off those wrappings and emit really clean, concise and fast code. How do I find out what the compiler decided to do?
The only way I know is to inspect the disassembly. This works well for simple code, b... | I'm afraid you're out of luck on this one. You're trying to find out "what the compiler did". What the compiler did is to produce machine code. The disassembly is simply a more readable form of the machine code, but it can't add information that isn't there. You can't figure out how a meat grinder works by looking at a... |
4,332,298 | 4,332,317 | Recursive function behavior in c++ | I know basic definition of recursive function.....but i want to know its impact on memory??
Why it is not chosen over loop or iteration?
| C++ does not mandate tail call optimization, so recursive functions that can trivially be converted to loops may still take up space linear in the call depth (storing the frame).
Additionally, C/C++ does not necessarily detect stack overflow, so that's another problem with potentially deep calls.
EDITED to have more qu... |
4,332,363 | 4,333,428 | c++ directed graph depth first search | I am attempting to write a method DFS method for a directed graph. Right now I am running into a segmentation fault, and I am really unsure as to where it is. From what I understand of directed graphs I believe that my logic is right... but a fresh set of eyes would be a very nice help.
Here is my function:
void wdig... | There are a few things you might want to consider. The first is that function level static variables are not usually a good idea, you can probably redesign and make those either regular variables (at the cost of extra allocations) or instance members and keep them alive.
The function assumes that the adjacency matrix i... |
4,332,398 | 4,337,745 | Boost::Python bindings for classes with inheritance | I'm trying to figure whats wrong with some autogenerated (with Pyste) boost::python code, but have no luck so far.
There is C++ library, Magick++, which provides two classes, Magick::Drawable and Magick::DrawableRectangle:
https://www.imagemagick.org/subversion/ImageMagick/trunk/Magick++/lib/Magick++/Drawable.h
class M... | If you want BP to implicitly convert objects foy you , you must tell BP that thay are implicitly convertable. put something like this in your bp::code:
boost::python::implicitly_convertible<SourceType,DestType>();
I do not know how to induce Pyste to do this.
|
4,332,426 | 4,332,442 | unsigned int value not giving correct result | following program should print "error" but its printing success.why?
#include<iostream>
using namespace std;
int main()
{
unsigned int a;
a=-10;
if(a == -10)
cout << "success" ;
else
cout << "error" ;
return 0;
}
| The conversion for comparison makes them equal again. But it should cause the compiler to emit a warning.
|
4,332,447 | 4,332,507 | Web Developer curious about developing for the Android | Hey there,
So I've been heavily focused on design/development using web technology for the last few years (php/mysql, javascript, etc), and I'm a bit hesitant to start learning C++.. At the same time, I see it as a potentially enjoyable learning experience.
To keep things brief, right now I'm developing an online app t... | Android development relies heavily on Java. So you are all ready on the right track.
However if you just want to make an app that brings people to your website, running javascript I am guessing, this is easy to do with android.
Android supports the webkit browser and has a view group called WebView. Your app can be... |
4,332,574 | 4,333,433 | What is the difference between a reference variable and a const pointer variable? |
Possible Duplicate:
Difference between pointer variable and reference variable in C++
This is a continuation of this question
Is a reference variable just another name of const pointer variable? If they are different what is the difference between a variable declared as a reference variable and a variable declared a... | OK. The problem is that there is no such thing like reference variable. Reference is not a variable at all. It is not an object. It actually has no size at all. It is just alternative name of the original object.
Check this:
struct A
{
int i[5];
};
int main()
{
std::cout << (sizeof(A&) == sizeof(A)) << std::endl... |
4,333,102 | 4,334,297 | "cannot find -ljscore" while I am trying to build Qt 4.7.1 static library | I tried to build static Qt library from the latest source, but got the following error:
/usr/bin/ld: cannot find -ljscore
collect2: ld returned 1 exit status
How to solve this problem?
| That's a bug in Qt's build system existing since 4.7.0 and not fixed in 4.7.1. After the failing make call, you have to copy libjscore.a and libjscore.prl (don't know their exact locations, search the Qt build tree to find them, somewhere in webkit) to the lib/ folder and rerun make.
|
4,333,123 | 4,333,254 | Why does ostream_iterator need to explicitly declare the type of objects to output? | In current C++, the class ostream_iterator was designed like the following:
// excerpted from the standard C++
template<class T, ...>
class ostream_iterator
{
public:
ostream_iterator(ostream_type&);
...
ostream_iterator<T,...>& operator =(const T&);
...
};
To me, this design is suboptimal. Because t... | It appears you could be right.
Let's see if we can construct an ostream_iterator that does not need a template argument.
The iterator works by copying values into it, so *iter = x; ++iter;
The iterator cheats by making operator* return itself and ++iter also returning itself without changing any state. The "magic" is i... |
4,333,170 | 4,333,270 | This iterator is not iterating, whats wrong? | Problem is that the iterator is not iterating through the loop. I don't know why. #includes are in the header as is my wont.
#include "neutronFileReader.h"
using namespace std ;
neutronFileReader::neutronFileReader()
{
}
list<vector<float> > neutronFileReader::spectrum(char* filename)
{
ifstream fin(filename) ;
... | You're not clearing out EnergyProbability between input loops. (*ns)[0] is therefore seeing the redundantly stored values from the first input, ignoring the new values which are actually in [2], then [4] etc.. Just add EnergyProbability.clear() before reading more values into it.
|
4,333,849 | 4,338,775 | What real platforms map hardware ports to memory addresses? | I sometimes see statements that on some platforms the following C or C++ code:
int* ptr;
*ptr = 0;
can result in writing to a hardware input-output port if ptr happens to store the address to which that port is mapped. Usually they are called "embedded platforms".
What are real examples of such platforms?
| Most systems in my experience use memory-mapped I/O. The x86 platform has a separate, non-memory-mapped I/O address space (that uses the in/out family of processor op-codes), but the PC architecture also extensively uses the standard memory address space for device I/O, which has a larger address space, faster access ... |
4,334,041 | 4,404,060 | OOP vs macro problem | I came across this problem via a colleague today. He had a design for a front end system which goes like this:
class LWindow
{
//Interface for common methods to Windows
};
class LListBox : public LWindow
{
//Do not override methods in LWindow.
//Interface for List specific stuff
}
class LComboBox : public LW... | Your colleague is probably thinking of the MFC message map macros; these are used in important-looking places in every MFC derived class, so I can see where your colleague is coming from. However these are not for implementing interfaces, but rather for details with interacting with the rest of the Windows OS.
Specif... |
4,334,057 | 4,334,198 | Inside a std::string, is it possible to find the first of a set of strings without using a loop? | Inside a std::string, is it possible to find the first of a set of strings without using a loop?
E.g.:
std::string str("aaa bbb ccc ddd eee fff ggg");
std::vector<std::string> vs;
vs.push_back("ccc");
vs.push_back("fff");
size_t pos = 0
pos = str.find(vs, pos); //< pseudo code
Thank you!
| You could split the string (using a stringstream) into a vector and then use std::find_first_of with the four iterators.
Here is a complete code example
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
#include <iterator>
using namespace std;
int main(void)
{
string st... |
4,334,293 | 4,335,642 | Boost: how to set program priority? | How to set program/thread priority (when talking about threads I mean ones that are created using Boost library) using Boost C++ library? I mean crossplatform way...
| There's no generalised cross-platform priority support in boost itself.
#ifdef is your friend...
See Tom's answer for the win32 solution.
On Linux you'd use the nice call (or possibly setpriority). Don't be put off by those document's statements that they adjust process priority; on Linux a thread is just a process wh... |
4,334,309 | 4,334,401 | Can I use the QT LPGL 2.1 commercially? | You might be reading this and about to flag it as a duplicate but wait. It's different from the others. I am wondering if I can use QT, under the LGPL 2.1 license. For single client programs. The programs are only made for one company to use.
Will LPGL be ok?
| The basic point of LGPL is that you can freely build anything on top of it as long as you are linking dynamically against the original binaries. Once you modify the library itself, you need to obey LGPL and distribute the code (but only for the library itself).
There are some distribution quirks, but invoking the libra... |
4,334,337 | 4,334,933 | C++ iterator for custom template class | I have nested iterator in my custom stack template class.
The problem I get now is that my nested iterator's constructor does not match when I create an iterator for my stack in the main. I wonder what the problem could be.
template <class T>
class stack
{
private:
int top;
T st[100];
public:
class my_iter... | It looks like you forgot a *:
class my_iterator
{
public:
my_iterator() : list(0), curr(0) {};
private:
stack<T>* pStack; // Pointer to a stack.
int curr;
};
Of course, you need more members (including better constructors) for the class. But this should at least allow you to create default iterators that d... |
4,334,339 | 4,334,405 | Disadvantages to using lots of if statements | Apart from code readability, why is it bad to use lots of if statements?
| If you have a lot of if statements one after the other, then a switch case statement is more useful. At least it has a fixed response time for each possible inupt as it does not need to fall through all the if statements.
A lot of if (and else) statement usually indicates
a) Violation of Single responsibility Principle... |
4,334,370 | 4,334,399 | Escape sequence \f - form feed - what exactly is it? | \f is said to be the form feed. \t is a tab, \a is a beep, \n is a newline. What exactly is a form feed - \f? The following program
#include <iostream>
int main()
{
std::cout << "hello\fgoodbye" << std::endl;
}
prints hello then a female sign (an upside down holy hand grenade:) and then goodbye all on one line.
| It skips to the start of the next page. (Applies mostly to terminals where the output device is a printer rather than a VDU.)
|
4,334,518 | 4,334,563 | Structure tag and name, why does a local variable declared as name compile? | In some code I saw recently there was a structure defined like this:
typedef struct tagMyStruct {
int numberOne;
int numberTwo;
} MYSTRUCT;
The way I understand this, tagMyStruct is the new data type and MYSTRUCT is a variable that is created right there.
At another place, this was used like this:
MYSTRUCT *pS... | No. tagMyStruct is the name of the struct. In C, unlike C++, you must explicitly use the struct keyword every time you use the struct type. For example
tagMyStruct x; //error
struct tagMyStruct x; //OK
To avoid writing struct all the time, struct tagMyStruct is typedef'd to MYSTRUCT. Now you can write
MYSTRUCT x; //ok... |
4,334,831 | 4,334,858 | What is a void pointer and what is a null pointer? | So I was going through some interview questions and I came across one about void and null pointers, which claims:
a pointer with no return type is called a null pointer. It may be any kind of datatype.
This confused me thoroughly! It seems void and null could be used interchangeably according to this question, and I ... | The two concepts are orthogonal:
A void pointer, (void *) is a raw pointer to some memory location.
A null pointer is a special pointer that doesn't point to anything, by definition. It can be a pointer to any type, void or otherwise.
A void pointer can be null or not:
void *void_ptr1 = nullptr;
void *void_ptr2 = mal... |
4,334,925 | 4,335,860 | visual studio linker warning LNK4098 | I have a dll project in which, when in Release configuration I build the project, I get the following warning:
MSVCRT.lib(cinitexe.obj) : warning
LNK4098: defaultlib 'msvcrtd.lib'
conflicts with use of other libs; use
/NODEFAULTLIB:library
It's just a warning but I dunno if this should be taken into account.
Fo... | It sounds like you could be running a debug library and a release compiled library in the same build.
Go through your project options and select to use the debug versions of any 3rd party libraries you use.
|
4,335,024 | 4,337,554 | Grammar of a C++ Translation Unit | My understanding, for a long time now, was that a C++ translation unit, after the preprocessor has run, is a sequence of declarations (let me remind that any definition is also a declaration).
Many people have argued with this statement but no one has ever given a counterexample. But I myself found this example which t... | An empty-declaration is allowed in (the current draft of) C++0x at file scope (and namespace scope and other places where a declaration is allowed) and it is just a semicolon. It is a standalone grammatical entity.
In C++03 a lone semicolon is not allowed where only a declaration is expected. Although it might appear t... |
4,335,043 | 4,537,162 | How to make use of existing operator<< overloads when logging with Pantheios? | If have a ton of user defined types which implement operator<< to write to an std::ostream. How can I uses these when logging my types with Pantheios?
| Well there is a way you can reuse the operator<< but it ain't pretty. I personally use the boost::lexical_cast library to convert almost any data-type to the std::string data type, which Pantheios supports natively. So if you have the operator<< defined for the point class then you could simply type:
pantheios::log_ERR... |
4,335,071 | 4,335,128 | why size of extreme down Derived class (multiple virtual inheritance) includes two times of size of member of superclass? | #include <iostream>
class SuperBase
{
public:
int Sb;
};
class Base1:virtual public SuperBase
{
public:
int a;
};
class Base2:virtual public SuperBase
{
public:
int b;
};
class Derived: public Base1,public Base2
{
public:
int c;
};
int main()
{
using namespace std;
cout<<sizeof(Derived);
re... | 24 is probably:
4 for Sb
4 for a
4 for b
4 for c
8 for the overhead of virtual inheritance.
On my (32bit) compiler, sizeof(Derived) is 24 and sizeof(Base1) is 12, though, suggesting that the overhead isn't always 8.
I would guess that the 8 consists of one vtable (or similar) pointer at the start of the Base1 subobje... |
4,335,170 | 4,335,239 | Accessing members in a C++ struct both dynamically and statically | I would like to have a struct (or something similar) in C++, that will allow access to its members dynamically. It should have a generic getter and setters that receive the member name as a string, and return some sort of variant type (e.g. boost::variant).
I was thinking it could be implemented using boost::fusion::ma... | fusion is an approach, but why not store your "fields" in a std::map keyed by a std::string, where the payload is the boost::variant...
i.e.
struct generic
{
std::map<std::string, boost::variant<foo, bar, bob, int, double> > _impl;
};
and then you can just lookup the key in your getter/setter...
heck, wrap the variant... |
4,335,288 | 4,335,553 | Virtual inheritance doesn't break static composition? | I was working the last 5 years with the assumption that virtual inheritance breaks static composition.
But now I discovered, that static composition is still maintained, there is just additional information about the location of the correct instance. Is this right?
| Data Layout in non-virtual Inheritance:
class Point2d {
int x_, y_;
};
class Point3d : public Point2d {
int z_;
};
Point2d:
+--------------+
| int x_ |
+--------------+
| int y_ |
+--------------+
Point3d:
+--------------+ --+
| int x_ | |
+--------------+ +-- Point2d subobject
| ... |
4,335,341 | 4,335,364 | How to build exe in Visual Studio C++ | I am a .NET C# developer and trying to learn C++.
I am having issues in trying to create an exe from a console app from Microsoft Visual Studio when I do a build compile and check the Debug folder. There isn't any exe, just some manifest files and other files. I am asking this because I am not sure if this is how it wo... | Have you checked the debug folder at the solution level? I believe this is the default target directory. The DEBUG folder in the project is for the output of temporary build files.
|
4,335,539 | 4,338,848 | How does boost::serialization Archive::register_type work? | boost::serialization is able to serialize my polymorphic objects of their most-derived class even if these objects are pointed by a reference/pointer to the base class. This without needing virtual functions.
To be able to do that, boost::serialization requires to know about existent polymorphic types: Archive::registe... | boost.serialization can write out your polymorphic class by using either typeid() or some user defined function get_key that returns the actual type of the polymorphic object.
register_type works by using the type supplied to instantiate a template that allows the archive to map the type identifier (either typeid(T) o... |
4,335,623 | 4,335,708 | Any way to use a method on a template class (when you have a pointer of a base class) when not knowing the used template type | Let's say I have this :
class A
{
virtual int Method2(){/*...*/}
};
template<typename T>
class B<T> : public A
{
public :
virtual int Method1(){/*...*/}
virtual int Method2(){/*...*/}
};
Is it possible to do something similar to this (this does not work of course...) ?
A* a = ...;
B* b = dynamic_cast<B*... | What people normally do is have an intermediary class.
class A { virtual ~A() {} };
class B : public A { virtual void method(); }
template<typename T> class C : public B {
void method() { ... }
};
A* a = new C<int>();
if(B* b = dynamic_cast<B>(a)) {
b->method();
}
This is known as type erasure. However, in th... |
4,335,716 | 4,337,045 | How to get Internet Explorer in a wxWidgets application? | Currently using wxHTML to display a remote web page in a C++ Windows wxWidgets based application.
However, I need more advanced features like rudimentary CSS styling and JavaScript. The easiest way, I guess, would be to embed Internet Explorer. Keeping the .exe size of the application small is key, so I don't think wxW... | I've done precisely this. It's fairly straightforward. Essentially, you host the MSHTML ActiveX control. Internet Explorer takes that control, and adds buttons, a history, new window functionality, tabs, etcetera. However, all the rendering, DOM, and Javascript parts are handled by the MSHTML component.
The wxActiveX c... |
4,335,962 | 4,336,298 | How to check if a template parameter is an iterator type or not? | template<class T>
struct is_iterator
{
static const bool value = ??? // What to write ???
};
int main()
{
assert(false == is_iterator<int>::value);
assert(true == is_iterator<vector<int>::iterator>::value);
assert(true == is_iterator<list<int>::iterator>::value);
assert(true == is_iterator<string::... | template<class T>
struct is_iterator
{
static T makeT();
typedef void * twoptrs[2]; // sizeof(twoptrs) > sizeof(void *)
static twoptrs & test(...); // Common case
template<class R> static typename R::iterator_category * test(R); // Iterator
template<class R> static void * test(R *); // Pointer
... |
4,335,988 | 4,339,430 | OpenCV (insufficient memory in function cvAlloc) | I made my simulation but I am faced with a problem. I'm getting images 640 x 480 in a video. But when it arrives at about 1600 frames or more I am faced with "insufficient memory (out of memory) in function cvAlloc". I released all the images and my RAM (mem storage) won't go over 28 MB. What should I do ?
| Did you check your RAM usage?
Have a look at OpenCV Memory Management. It lists some common techniques to fix memory leaks.
|
4,336,536 | 4,336,570 | Ubuntu:C++::Boost library upgrade | After installing Boost library using Synaptic Package Manager, the version installed is 1.42.
If I check on boost official website, the current version is: 1.45.
How can I upgrade to 1.45 from Synaptic package manager?
Thanks in advance.
| You probably can not as the distribution usually lags behind. The best option I usually follow is to just download and compile and install it myself as described here
|
4,336,710 | 4,336,727 | Commonly Accepted Variable Name Formatting - C/C++ | I realize that this can be a matter of preference, but I have noticed that variables names in a lot of code samples I've seen have a prefix of g_, s_, m_, or just _. Is this a commonly accepted practice, and what do these prefixes mean? Are there any others that would be good to know?
|
g_ is a global variable
s_ is a static
m_ is a member (an instance variable)
_ is either a member, or more specifically a private member (both usages turn up)
This is common enough that many developers know about it, although it is not (to my knowledge) universally accepted. I don't think you are missing any others.
... |
4,336,860 | 4,336,899 | Is "++l *= m" undefined behaviour? | I have started studying about C++0x. I came across the follow expression somewhere:
int l = 1, m=2;
++l *= m;
I have no idea whether the second expression has well defined behavior or not. So I am asking it here.
Isn't it UB? I am just eager to know.
| In the code above, prefix ++ has precedence over *=, and so gets executed first. The result is that l equals 4.
UPDATE: It is indeed undefined behavior. My assumption that precedence ruled was false.
The reason is that l is both an lvalue and rvalue in *=, and also in ++. These two operations are not sequenced. Hence l... |
4,336,871 | 4,337,075 | Programmatically Interrupting Serial I/O when USB Device is Removed - C++ | I have an application wherein serial I/O is conducted with an attached USB device via a virtual COM port. When surprise removal of the device is detected, what would be the best way to stop the serial I/O. Should I simply close the port? Or, should there be a global variable, which is maintained to indicate the pres... | I'm assuming you are running Windows.
This depends on how you have designed your communication flow.
I have a BasePort object where I have derived a COMPort object (and many other communication objects). The COMPort object creates one TXThread and RXThread class. These threads are waiting for the "OVERLAP" to signal th... |
4,337,177 | 4,852,884 | Compiling C++ code with cygwin for JNI (Android NDK) | I'm trying to build a C++ file for using in my Android application over JNI. I'm building in Windows using Cygwin. I'm completely new to this and don't know what I am doing.
Here's part of the output:
$ g++ -c test_wrap.cxx -I"C:\dev\android-ndk-r4b\build\platforms\android-4\arch-arm\usr\include" -I./include
In file i... | The answer was simply to create an Android.mk file and use the ndk-build command.
|
4,337,228 | 4,337,312 | protected ifstream member | I am close to completion of my first OOP project, coming from a C background. I was wondering a design issue related to some ifstream object that I use in the base class to open a file. After that I would like to use the same stream to do further operation by the derived classes. I defined only this member as a protect... | protected is ideal for preserving encapsulation, if it's integral to your design that the derived classes have the same I/O functionality as the base class.
Encapsulation does not mean everything has to be private, it means that each data or code member of a given class is visible only to the minimal set of class use... |
4,337,306 | 4,337,370 | Type Conversion/Casting Confusion in C++ | What is Type Conversion and what is Type Casting?
When should I use each of them?
Detail: Sorry if this is an obvious question; I'm new to C++, coming from a ruby background and being used to to_s and to_i and the like.
| Conversion is when a value is, um, converted to a different type. The result is a value of the target type, and there are rules for what output value results from what input (of the source type).
For example:
int i = 3;
unsigned int j;
j = i; // the value of "i" is converted to "unsigned int".
The result is the unsign... |
4,337,327 | 4,337,794 | Failing to read values from a file | The program below should read in a bunch of integers from a file and work out their average:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main( int argc, char** argv )
{
ifstream fin( "mydata.txt" );
int i, value, sum = 0;
for ( i = 0; fin >> value;... | i guess mydata.txt is not in the same directory as the executable, the code works for me
|
4,337,494 | 4,337,591 | If JNI DeleteGlobalRef() is called, does the corresponding java object get garbage collected? | What I mean is, if I create a global reference jobject in C++, and then pass that off to some Java code, and delete call DeleteGlobalRef(), is that underlying java object potentially garbage collected right away, so that any future Java code that is already refering to that object might come back with a NullPointerExce... | DeleteGlobalRef() frees the reference, not the object.
If that was the last reachable reference, then the referenced object is available for garbage collection.
Is a "GlobalReference" on an object just a reference count to the object
No. It's just a reference that remains valid until you free it explicitly. Java's g... |
4,337,642 | 4,337,717 | How to output a float neither in scientific, nor in fixed point notation in std::cout? | #include <iostream>
int main()
{
float test = 12535104400;
std::cout << test;
std::cin.get();
return 0;
}
//on msvc 2010 this ouputs: 1.25351e+010
I would like it to output just "12535104400" or in other words, the human readable format which has no leading zeros, but outputs the full value of a n... | The particular number cannot be accurately represented, for example try the following:
float v = 12535104400;
cout.precision(0);
cout << fixed << v << endl;
You'll see it outputs: 12535104512
|
4,337,905 | 4,338,201 | C++ How can I use template collections of template objects with inheritance? | Okay... first off I'm just going to explain something about what the architecture I'm after looks like.
I am trying to implement a Stats Manager for my Stats objects. This stats manager is designed using templates (see declaration in the pic).The StatMgr holds a map (not STL) that maps a string implementation to a sma... | Put template code directly in the header, not in a separate CPP file.
See this previous question for background.
EDIT: btw I see you are on a very old compiler - this problem may be insurmountable, even VC6 was sketchy for templates.
|
4,338,067 | 4,338,115 | Convert std::string to QString | I've got an std::string content that I know contains UTF-8 data. I want to convert it to a QString. How do I do that, avoiding the from-ASCII conversion in Qt?
| There's a QString function called fromUtf8 that takes a const char*:
QString str = QString::fromUtf8(content.c_str());
|
4,338,073 | 4,338,232 | Implementation supplied copy constructor and assignment operator | I have a small confusion regarding the situations where the implementation (compiler) will not supply the copy constructor and the copy assignment operator.
When we declare the copy ctor and/or copy assignment operator in our class.
Some says when we derive from a class which has a private copy ctor and/or copy assign... | Regarding the copy constructor, this is what the standard says (12.8/7) :
A program is illformed if the class
for which a copy constructor is
implicitly defined has:
a nonstatic data member of class type (or array thereof) with an
inaccessible or ambiguous copy
constructor, or
a base class with an inaccessibl... |
4,338,085 | 4,338,124 | How do I check if a const char*'s value is defined? | My application reads settings from a conf file first, and then those options can be overwritten from the cli arguments. After it loads the settings from the conf, I need to check if the require values are set but I'm stuck at making it check the variables.
Sample code:
#include <stdio.h>
int main() {
const char* test... | You didn't initialize test. If you want it to be NULL initially, you have to set it:
const char* test = NULL;
|
4,338,238 | 4,338,270 | Runing a cpp binary on php could speed up my code? | I'm a php developer as well as cpp developer. I was wondering: if I make a cpp binary and I run it on php. Will that make my process run faster?
For example:
I have to compare 1,000 array elements and execute a process for each of them and in some cases I had to run it over and over again ( recursively) . Yes is mes... |
Yes, this might be faster. It's also very hard to do right (lots of corner cases in IPC).
Don't try this unless it's absolutely necessary for performance. First try to improve the algorithm in PHP.
Don't use the C++ code in production until you've measured the difference, and the C++ solution is significantly faster.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.