question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,040,504 | 1,041,141 | Any way to get the AtomineerUtils addin to ignore __declspecs? | I'm evaluating the AtomineerUtils addin (which allows Visual Studio to auto-enter doxygen comment blocks).
It misfires slightly when I have a class definition that has __declspec (dllexport) in it. That is, instead of the class name appearing in the comment block it adds, it uses the word declspec.
Small annoyance, bu... | Wow.... shot off an email to the Atomineer developer at the same time I posted this. He just got back to me, his new version 5.97 fixes this!
|
1,040,914 | 1,040,990 | how to Ignore definitions (VS2008) | i have some sourcecode that I want to compile with VS2008 but there are many errors i have to fix.
Now there are some Enums like:
enum
{
BACKGROUND = 0x00000001,
WEAPON = 0x00000002,
TRANSPARENT = 0x00000004
}
The problem is that TRANSPARENT is defined as:
#define TRANSPARENT 1
in WinGDI.h
That will ca... | You can use
#undef TRANSPARENT
but that may cause errors elsewhere, if the WinGDI TRANSPARENT is used afterwards. A (messy) workaround could be:
#ifdef TRANSPARENT
#define _TRANSPARENT TRANSPARENT
#undef TRANSPARENT
#endif
and after your code:
#ifdef _TRANSPARENT
#define TRANSPARENT _TRANSPARENT
#endif
|
1,040,950 | 1,040,994 | Reference-type conversion operators: asking for trouble? | When I compile the following code using g++
class A {};
void foo(A&) {}
int main()
{
foo(A());
return 0;
}
I get the following error messages:
> g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:10: error: invalid initialization of non-const reference of type ‘A&’ from a temporary of type ‘A... | It isn't that an address can't be taken (the compiler could always order it shoved on the stack, which it does with ref-to-const), it's a question of programmers intent. With an interface that takes a A&, it is saying "I will modify what is in this parameter so you can read after the function call". If you pass it a te... |
1,041,074 | 1,041,122 | throwing exceptions of objects on the stack, mem leak with new? | Is it a bug to do this:
if(some_error)
throw Cat("Minoo");
Where Cat is a class.
Then in some other function that called the method that threw the exception...
I would have:
catch(const Cat &c)
{
}
If it is invalid, do I use new Cat("Minoo");
Would that cause a memory leak?
| 1) Invalid? No, that's precisely what you're supposed to do: throw an object. The object in the throw-statement may be on the stack, but it is copied when it is thrown. Compare, for example, the effect of executing return Cat("Minoo");
2) Will throwing a pointer cause the pointed-to object to be leaked? Yes, if the ... |
1,041,167 | 1,041,171 | Rethrowing from caught | If I throw an exception:
throw Cat("Minoo");
Then I catch and rethrow with ... at some lower level in the call stack:
catch(...)
{
throw;
}
Then at some other lower level in the call stack I try to catch with:
catch(const Cat& c)
{
//Will it enter here, and if so will c be valid data?
}
catch(...)
{
}
| Yes, this is correct. This is addressed in the very next question of the section of the C++ FAQ that I linked you to on your previous question.
|
1,041,218 | 1,041,263 | The "Self-Factory" Pattern | I don't know if there is an official name for this, but I have been playing with what I like to call the "self-factory" pattern. Basically, it's when an abstract base class acts as a factory for itself. Let me explain:
I have Foo objects and Bar objects in my system, which are used via interfaces FooInterface and Bar... | Factories have two common uses:
1) Decide dynamic polymorphic type at runtime, based on parameters and/or global state (such as configuration). Your pattern does this.
2) Dependency injection: rather than using a static function to create objects, use a factory object, so that the type of object returned can be configu... |
1,041,342 | 1,041,417 | Fluent interfaces and inheritance in C++ | I'd like to build a base (abstract) class (let's call it type::base) with some common funcionality and a fluent interface, the problem I'm facing is the return type of all those methods
class base {
public:
base();
virtual ~base();
base& with_foo();
base& with_bar();
protected:
... | This problem of "losing the type" can be solved with templates - but it's rather complicated.
Eg.
class Pizza
{
string topping;
public:
virtual double price() const;
};
template <class T, class Base>
class FluentPizza : public Base
{
T* withAnchovies() { ... some implementation ... };
};
class RectPizza : publi... |
1,041,618 | 1,041,653 | Is using *this a good idea? | I'm not sure if
return *this
is the only way we could return an instance of a class who called a member function? The reason why I asked is because our instructor told us to avoid using pointers if necessary and I'm wondering if this is a case where the only necessary way to do it is by returning the this pointer.
I... | Get a new instructor. It looks as if the declaration of plus() is completely wrong.
it probably should return a value rather than a reference
if it must return a reference, it should return a const reference
it should definitely take a const reference as a parameter
That is for likely sensible implementations of a m... |
1,041,620 | 1,041,939 | What's the most efficient way to erase duplicates and sort a vector? | I need to take a C++ vector with potentially a lot of elements, erase duplicates, and sort it.
I currently have the below code, but it doesn't work.
vec.erase(
std::unique(vec.begin(), vec.end()),
vec.end());
std::sort(vec.begin(), vec.end());
How can I correctly do this?
Additionally, is it faster to eras... | I agree with R. Pate and Todd Gardner; a std::set might be a good idea here. Even if you're stuck using vectors, if you have enough duplicates, you might be better off creating a set to do the dirty work.
Let's compare three approaches:
Just using vector, sort + unique
sort( vec.begin(), vec.end() );
vec.erase( unique... |
1,041,866 | 1,041,880 | What is the effect of extern "C" in C++? | What exactly does putting extern "C" into C++ code do?
For example:
extern "C" {
void foo();
}
| extern "C" makes a function-name in C++ have C linkage (compiler does not mangle the name) so that client C code can link to (use) your function using a C compatible header file that contains just the declaration of your function. Your function definition is contained in a binary format (that was compiled by your C++ c... |
1,042,107 | 1,042,120 | Compiler not flagging incorrect return value for HRESULT | I just spent way too long trying to diagnose why, in the following snippet of code, the ProcessEvent() method seemed to be ignoring the false value I passed in for aInvokeEventHandler:
HRESULT
CEventManager::
Process(Event anEvent)
{
return (m_pPool->GetFsm()->ProcessEvent(anEvent), false);
}
// Definition of Pro... | You are suffering from the comma operator, which evaluates and discards the value of its left-hand operand, and then evaluates its right-hand operand as the value of the expression.
Also, the default value for the argument to ProcessEvent is why your one-argument call was acceptable.
|
1,042,110 | 12,762,166 | Using scanf() in C++ programs is faster than using cin? | I don't know if this is true, but when I was reading FAQ on one of the problem providing sites, I found something, that poke my attention:
Check your input/output methods. In C++, using cin and cout is too slow. Use these, and you will guarantee not being able to solve any problem with a decent amount of input or outp... | Here's a quick test of a simple case: a program to read a list of numbers from standard input and XOR all of the numbers.
iostream version:
#include <iostream>
int main(int argc, char **argv) {
int parity = 0;
int x;
while (std::cin >> x)
parity ^= x;
std::cout << parity << std::endl;
return 0;
}
sca... |
1,042,277 | 1,044,237 | Literate Coding Vs. std::pair, solutions? | As most programmers I admire and try to follow the principles of Literate programming, but in C++ I routinely find myself using std::pair, for a gazillion common tasks. But std::pair is, IMHO, a vile enemy of literate programming...
My point is when I come back to code I've written a day or two ago, and I see manipulat... | How about this:
struct MyPair : public std::pair < int, std::string >
{
const int& keyInt() { return first; }
void keyInt( const int& keyInt ) { first = keyInt; }
const std::string& valueString() { return second; }
void valueString( const std::string& valueString ) { second = valueString; }
};
It's a b... |
1,042,281 | 1,042,329 | c++ for loop temporary variable use | Which of the following is better and why? (Particular to c++)
a.
int i(0), iMax(vec.length());//vec is a container, say std::vector
for(;i < iMax; ++i)
{
//loop body
}
b.
for( int i(0);i < vec.length(); ++i)
{
//loop body
}
I have seen advice for (a) because of the call to length function. This is bothering me. D... | Example (b) has a different meaning to example (a), and the compiler must interpret it as you write it.
If, (for some made-up reason that I can't think of), I wrote code to do this:
for( int i(0);i < vec.length(); ++i)
{
if(i%4 == 0)
vec.push_back(Widget());
}
I really would not have wanted the compiler to ... |
1,042,392 | 1,042,397 | <operator missing when iterating through c++ map | The following code does not want to compile. See the included error message.
Code:
#include <map>
#include <vector>
#include <iostream>
class MapHolder {
public:
std::map<std::vector<std::string>,MapHolder> m_map;
void walk_through_map() {
std::map<std::vector<std::string>,MapHolder>::iterator it;
... | Use != instead of < in iterator comparison.
|
1,042,415 | 1,066,246 | Windows XP Style: Why do we get dark grey background on static text widgets? | We're writing Windows desktop apps using C++ and Win32. Our dialog boxes have an ugly appearance with "Windows XP style": the background to the static text is grey. Where the dialog box background is also grey, this is not a problem, but inside a tab control, where the background is white, the grey background to the... | We're not overriding the WM_CTLCOLORSTATIC message. There's no occurrence of this string in our source code and nothing like it in our message handlers.
We've worked around this problem by overriding the WM_DRAWITEM message for tab controls to paint their contents with the grey background (standard for dialog boxes wi... |
1,042,507 | 1,042,523 | Finding smallest value in an array most efficiently | There are N values in the array, and one of them is the smallest value. How can I find the smallest value most efficiently?
| If they are unsorted, you can't do much but look at each one, which is O(N), and when you're done you'll know the minimum.
Pseudo-code:
small = <biggest value> // such as std::numerical_limits<int>::max
for each element in array:
if (element < small)
small = element
A better way reminded by Ben to me was ... |
1,042,855 | 1,448,859 | Using Boost to read and write XML files | Is there any good way (and a simple way too) using Boost to read and write XML files?
I can't seem to find any simple sample to read XML files using Boost. Can you point me a simple sample that uses Boost for reading and writing XML files?
If not Boost, is there any good and simple library to read and write XML files t... | You should Try pugixml Light-weight, simple and fast XML parser for C++
The nicest thing about pugixml is the XPath support, which TinyXML and RapidXML lack.
Quoting RapidXML's author "I would like to thank Arseny Kapoulkine for his work on pugixml, which was an inspiration for this project" and "5% - 30% faster than p... |
1,042,940 | 1,043,053 | writing directly to std::string internal buffers | I was looking for a way to stuff some data into a string across a DLL boundary. Because we use different compilers, all our dll interfaces are simple char*.
Is there a correct way to pass a pointer into the dll function such that it is able to fill the string buffer directly?
string stringToFillIn(100, '\0');
Function... | I'm not sure the standard guarantees that the data in a std::string is stored as a char*. The most portable way I can think of is to use a std::vector, which is guaranteed to store its data in a continuous chunk of memory:
std::vector<char> buffer(100);
FunctionInDLL(&buffer[0], buffer.size());
std::string stringToFill... |
1,043,034 | 1,043,107 | What does void mean in C, C++, and C#? | Looking to get the fundamentals on where the term "void" comes from, and why it is called void. The intention of the question is to assist someone who has no C experience, and is suddenly looking at a C-based codebase.
| Basically it means "nothing" or "no type"
There are 3 basic ways that void is used:
Function argument: int myFunc(void)
-- the function takes nothing.
Function return value: void myFunc(int)
-- the function returns nothing
Generic data pointer: void* data
-- 'data' is a pointer to data of unknown type, and cannot be ... |
1,043,114 | 1,043,243 | How to buffer output from a .net BackgroundWorker? | I have a stream of data coming in from an external source which I currently collect in a BackgroundWorker. Each time it gets another chunk of data, it presents that data to a GUI using a ReportProgress() call.
I get the impression that the ProgressChanged function is just a synchronisation mechanism though so when my w... | The worker thread just sends an async message to the gui thread, which will result in an event firing in the GUI. It shouldn't halt your background thread.(and that shouldn't matter anyway. Your GUI program could halt for a long time if the user decided to start another program, etc.)
You don't talk about what kind of ... |
1,043,402 | 1,043,424 | Why does this code crash at the places mentioned? | Can you please elaborate why this code crashes at the places mentioned? I am a bit stumped on this. I guess that it has got something to do with sizeof(int) but I am not so sure. Can anybody explain?
class Base
{
public:
virtual void SomeFunction()
{
printf("test base\n");
}
int m_j;
};
class... | Quote from this FAQ: Is array of derived same as as array of base?
Derived is larger than Base, the pointer arithmetic done with 2nd object baseArray is
incorrect: the compiler uses sizeof(Base) when computing the address
for 2nd object, yet the array is an array of Derived, which means
the address computed (an... |
1,043,670 | 1,043,788 | Do you know which library Firefox 3 uses for the "download completed" info? | It's the window that shows up when you set showAlertOnComplete = true.
about:config
browser.download.manager.showAlertOnComplete = true
I want to add notification messages in my applications and I need to find a good open source library for that task.
| There are a few ways of doing notifications.
In terms of open source libraries, there are a number of system-wide notification schemes, such as Snarl (Windows), Growl (Mac) or Mumbles (Linux).
If you to work only with what is already on the platform, there are some related questions on SO around the Windows API for not... |
1,043,766 | 1,043,834 | Convert BYTE buffer (0-255) to float buffer (0.0-1.0) | How can I convert a BYTE buffer (from 0 to 255) to a float buffer (from 0.0 to 1.0)? Of course there should be a relation between the two values, eg: 0 in byte buffer will be .0.f in float buffer, 128 in byte buffer will be .5f in float buffer, 255 in byte buffer will be 1.f in float buffer.
Actually this is the code t... | Whether you choose to use a lookup table or not, your code is doing a lot of work each loop iteration that it really does not need to - likely enough to overshadow the cost of the convert and multiply.
Declare your pointers restrict, and pointers you only read from const. Multiply by 1/255th instead of dividing by 255.... |
1,043,825 | 1,044,677 | Process name change at runtime (C++) | Is it possible to change the name(the one that apears under 'processes' in Task Manager) of a process at runtime in win32? I want the program to be able to change it's own name, not other program's. Help would be appreciated, preferably in C++. And to dispel any thoughts of viruses, no this isn't a virus, yes I know wh... | I know you're asking for Win32, but under most *nixes, this can be accomplished by just changing argv[0]
|
1,044,088 | 1,044,133 | How to split the strings in vc++? | I have a string "stack+ovrflow*newyork;" i have to split this stack,overflow,newyork
any idea??
| First and foremost if available, I would always use boost::tokenizer for this kind of task (see and upvote the great answers below)
Without access to boost, you have a couple of options:
You can use C++ std::strings and parse them using a stringstream and getline (safest way)
std::string str = "stack+overflow*newyork;"... |
1,044,103 | 1,044,296 | DebugBreak not breaking | I'm writing a class in C++ that I cannot debug by using F5. The code will run from another "service" that will invoke it.
In the past I've used __debugbreak() and when I got a window telling me that an exception was thrown selected to debug it.
Recently I've updated to windows 7 and it kept working for a while.
Today ... | Finally I found the cause of the issue.
It's a Vista/Win7 cause:
Open The Action center control
Goto Action Center settings
Goto Problem Reporting Settings
Choose "Each time a problem occurs, ask me before checking for solution"
Although this is more of IT solution/question I've been plagued with this problem all day... |
1,044,313 | 1,124,601 | How to use DSP to speed-up a code on OMAP? | I'm working on a video codec for OMAP3430. I already have code written in C++, and I try to modify/port certain parts of it to take advantage of the DSP (the SDK (OMAP ZOOM3430 SDK) I have has an additional DSP).
I tried to port a small for loop which is running over a very small amount of data (~250 bytes), but about... | From the measurements I did, one messaging cycle between CPU and DSP takes about 160us. I don't know whether this is because of the kernel I use, or the bridge driver; but this is a very long time for a simple back & forth messaging.
It seems that it is only reasonable to port an algorithm to DSP if the total computati... |
1,044,378 | 1,044,418 | What is a good project / way for an out of practice C++ developer to get back into it? | Like many people here, I started my programming experience with the good ol' green screen BASIC that you get when you booted an Apple II without a disk. I taught myself C++ in my teens, and even took a class on it in college, but as soon as I discovered .NET and C#, I dropped C++ like a bad habit. Now, (many) years lat... | Try Euler Project
Project Euler is a series of
challenging mathematical/computer
programming problems that will require
more than just mathematical insights
to solve. Although mathematics will
help you arrive at elegant and
efficient methods, the use of a
computer and programming skills will
be require... |
1,044,448 | 1,046,317 | Why does boost::variant not provide operator != | Given two identical boost::variant instances a and b, the expression ( a == b ) is permitted.
However ( a != b ) seems to be undefined. Why is this?
| I think it's just not added to the library. The Boost.Operators won't really help, because either variant would have been derived from boost::operator::equality_comparable. David Pierre is right to say you can use that, but your response is correct too, that the new operator!= won't be found by ADL, so you'll need a ... |
1,044,517 | 1,445,821 | Unpacking an executable from within a library in C/C++ | I am developing a library that uses one or more helper executable in the course of doing business. My current implementation requires that the user have the helper executable installed on the system in a known location. For the library to function properly the helper app must be in the correct location and be the cor... | You can use xxd to convert a binary file to a C header file.
$ echo -en "\001\002\005" > x.binary
$ xxd -i x.binary
unsigned char x_binary[] = {
0x01, 0x02, 0x05
};
unsigned int x_binary_len = 3;
xxd is pretty standard on *nix systems, and it's available on Windows with Cygwin or MinGW, or Vim includes it in the... |
1,044,665 | 1,044,683 | BSD Socket issue: inet_ntop returning "0.0.0.0" | I'm trying to get the IP of the machine a socket I've bound is listening on. The port number printed works fine, but the address is "0.0.0.0". Here's the relevant code. res has been passed to getaddrinfo and getsockname before getting to this code.
char ip[INET_ADDRSTRLEN];
struct sockaddr_in *ipv4 = (struct sockaddr_i... | An address of 0.0.0.0 means that the socket is listening on all addresses. A specific address like 127.0.0.1 would mean that the server is just listening on that address, but not on any other ones.
|
1,044,703 | 1,044,732 | How do you pass boost::bind objects to a function? | I have a one-dimensional function minimizer. Right now I'm passing it function pointers. However many functions have multiple parameters, some of which are held fixed. I have implemented this using functors like so
template <class T>
minimize(T &f) {
}
Functor f(param1, param2);
minimize<Functor>(f);
However the f... | You can just use boost::function. I think boost::bind does have its own return type, but that is compatible with boost::function. Typical use is to make a typedef for the function:
typedef boost::function<bool(std::string)> MyTestFunction;
and then you can pass any compatible function with boost::bind:
bool SomeFuncti... |
1,044,968 | 1,052,817 | Does Visual C++ 2010 Beta 1 have unique_ptr, and if not, where can I get a C++0x reference implementation? | I do know:
It wasn't in the CTP
It's slated to be in the final release
I can't find it in Beta 1
I want to play with it
| It's in the same header as shared_ptr :
#include <memory>
|
1,045,232 | 1,436,004 | Automating RegisterClass in C++ Builder VCL | We use C++ Builder for an application whose forms are kept external to the EXE in a database. Application code is C++
This allows us to modify the forms and form/actions without a re-compile. Here is a snippet of code that gets the job done of loading a form.
RegisterClass(__classid(TButton));
RegisterClass(__class... | The approach you have here is exactly right, in my opinion. I took the same approach years ago using Delphi2, although I had to implement my own class factory and ObjectToText/TextToObject functions as ReadComponent() never featured in the VCL.
On your second point of only registering required classes, surely they onl... |
1,045,530 | 1,045,567 | How to set TCP_NODELAY on BSD socket on Solaris? | I am trying to turn off Nagle's algorithm for a BSD socket using:
setsockopt(newSock, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof flag);
but the compiler claims TCP_NODELAY hasn't been seen before:
error: `TCP_NODELAY' undeclared (first use this function)
This is the full list of includes for the file this is in:
... | Looks like you are missing #include <netinet/tcp.h> - that's where TCP_... defines live.
|
1,045,675 | 2,390,777 | DirectX post-processing shader | I have a simple application in which I need to let the user select a shader (.fx HLSL or assembly file, possibly with multiple passes, but all and only pixel shader) and preview it.
The application runs, the list of shaders comes up, and a button launches the "preview window."
From this preview window (which has a Dire... | Try clearing the depth-stencil buffer after each time you render the quad.
|
1,045,925 | 1,114,424 | Transparent windows with Linux | I am trying to find a cross linux distribution solution to the problem of making a program have transparent windows.
I now there is some methods out there, that take screen shots of the windows underneath and then print them as the background of the image. I would prefer not to uses that method because it likely that ... | You can take a look at the code of the X terminal emulators, KTerm for KDE or Gnome Terminal for gnome (depending of your target platform). I think these are the best examples of apps that implement transparency. I think that you can even find in that code solutions for getting transparency when compiz is not available... |
1,045,985 | 1,046,073 | What is the best practice regarding const instance methods? | In light of the accepted answer pointing out that returning a non-const reference to a member from a const instance method won't compile (without a cast or making the member variable mutable), the question has become more a general best-practices discussion of const instance methods.
For posterity, here's the original ... | const (when applied to a member function) is mainly useful as a means of self documenation. It is a contract with the calling code that this function will not modify the external state (i.e. have no observable side effects).
The compilier achieves this by making all members effectively const while inside a const mem... |
1,046,068 | 1,046,099 | Would one have to know the machine architecture to write code? | Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?
IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to both... | correct for most circumstances
The runtime/language/compiler will abstract those details unless you are dealing directly with word sizes or binary at a low level.
Even byteorder is abstracted by the NIC/Network stack in the kernel. It is translated for you. When programming sockets in C, you do sometimes have to deal w... |
1,046,078 | 1,046,102 | Best practices: syncing between threads | Is if almost always required to have thread syncing (i.e. use of mutex, semaphores, critical sections, etc.) when there is cross-thread data accessing, even if it's not required after going through a requirements analysis?
| I would always recommended going with the simplest, most straightforward synchronization scheme until analysis shows you should do otherwise - this usually means a few large locks versus many fine-grained locks or lockfree.
The issue is that determining if lock-free code is correct is much more difficult than determini... |
1,046,248 | 1,055,611 | What are some recommended frameworks for manipulating spatial data in C++? | What are some recommended frameworks for manipulating spatial data in C++?
I'm looking for a polygon object, point object, and some operations like union, intersection, distance, and area. I need to enter coordinates in WGS84 (lon,lat) and get area in square km.
I would prefer a free/open source framework, but am o... | GEOS is an open source (LGPL) C++ geometry / topology engine. Might suit you?
Useful places to look for this stuff are this useful article on the O'Reilly website and also OSGeo which is a collaboration to support open source geospatial stuff.
|
1,046,322 | 1,046,403 | How do I determine a maximum time needed for TCP socket to die due to intermediate network disconnect? | I have a program in C++, using the standard socket API, running on Ubuntu 7.04, that holds open a socket to a server. My system lives behind a router. I want to figure out how long it could take to get a socket error once my program starts sending AFTER the router is cut off from the net.
That is, my program may go idl... | You should be able to use:
http://linux.die.net/man/2/getsockopt
with:
SO_RCVTIMEO and SO_SNDTIMEO
to determine the timeouts involved.
This link: http://linux.die.net/man/7/socket
talks about more options that may be of interest to you.
In my experience, just picking a time is usually a bad idea. Even when it sounds r... |
1,046,477 | 1,046,503 | Is there any reason to use the 'auto' keyword in C++03? |
Note this question was originally posted in 2009, before C++11 was ratified and before the meaning of the auto keyword was drastically changed. The answers provided pertain only to the C++03 meaning of auto -- that being a storage class specified -- and not the C++11 meaning of auto -- that being automatic type deduc... | auto is a storage class specifier, static, register and extern too. You can only use one of these four in a declaration.
Local variables (without static) have automatic storage duration, which means they live from the start of their definition until the end of their block. Putting auto in front of them is redundant si... |
1,046,499 | 1,046,515 | How do I call managed .NET code from my un-managed C++ code in Windows and vice versa? | I have a pure C++ application developed using VC 6.0. I would like this application to make use of a library developed in C#. How do I call the methods in the C# library from my native executable? I do not want to convert my un-managed C++ native application to managed code. Similarly, how do I do the reverse? Is PInvo... | To call into managed code from unmanaged C++, use ClrCreateManagedInstance, or export your types in your managed assembly as COM visible, and use COM. To call into unmanaged code from managed, use COM or P/Invoke.
|
1,046,547 | 1,046,603 | Is there an automatic source code formatter that nicely wraps lines of C/C++? | I use astyle to format my code most of the time, and I love it, but one annoyance is that it can't specify at least a "hint" for max line length. If you have a line of code like:
this->mButtonCancel->setLeftClickProc(boost::bind(&FileListDialog::cancelLeftClick, this));
I would like a source code formatter to be able... | GNU Indent has support for breaking long lines.
http://www.gnu.org/software/indent/manual/indent.html#SEC12
|
1,046,660 | 1,046,710 | How to build a Visual Studio 9.0 solution from Cygwin and get build output? | I am trying to set up an automated build system on Windows using Cygwin. Among other things, it needs to be able to build several Visual C++ solutions. I have a script which sets up the environment variables needed for devenv, and if I type 'devenv' in bash it brings up the Visual Studio IDE. No problems so far.
I am... | Will cygwin find and run .com files?
There are 2 devenv executables, one is devenv.com which is a console mode application that handles stdin, stdout and stderr proxying for the other executable, devenv.exe, which is a GUI mode application. If devenv.exe is what cygwin is loading then there will be no stdin/stdout s... |
1,046,714 | 1,049,643 | What is a good random number generator for a game? | What is a good random number generator to use for a game in C++?
My considerations are:
Lots of random numbers are needed, so speed is good.
Players will always complain about random numbers, but I'd like to be able to point them to a reference that explains that I really did my job.
Since this is a commercial project... | George Marsaglia has developed some of the best and fastest RNGs currently available
Multiply-with-carry being a notable one for a uniform distribution.
=== Update 2018-09-12 ===
For my own work I'm now using Xoshiro256**, which is a sort of evolution/update on Marsaglia's XorShift.
=== Update 2021-02-23 ===
In .NET 6 ... |
1,046,717 | 1,046,758 | Polymorphic member function pointer | I'm trying to write a callback event system in DirectX9. I'm attempting to use method function pointers to trigger events to mouseclicks; but I'm having some problems. My game uses a gamestate manager to manage the rendering. All of my gamestates are derived from a base class AbstractGameState.
I have a sprite object w... | I don't really know why your assignment is not working, no doubt litb will be along shortly to explain why. Boost.Function is a beautiful, generic, typesafe and standard function object that can be used as a replacement for function pointers in almost all circumstances. I would do this:
typedef boost::function0<void> E... |
1,046,753 | 1,046,771 | help with explicit template especialization | thank you for looking
i got this example from my book but i cant understand why the line
S<void,int> sv; // uses Template at (2)
but
S<void,char> e2;
//uses (1) when im thinking it would use (2) especialization as well
could anyone explain the behavior?
btw all the comments in code below are from book author... | Why should it use (2)?
(2) is a specialization of S<void, int>. What you have is S<void, char>. The types are different, so the specialization isn't used. Specializations only apply if they match exactly. It's not good enough that "a char can be implicitly promoted to an int". If no specialization exists for S<void, ch... |
1,046,801 | 1,046,867 | Why doesn't this C++0x code call the move constructor? | For some reason, the following code never calls Event::Event(Event&& e)
Event a;
Event b;
Event temp;
temp = move(a);
a = move(b);
b = move(temp);
why not?
Using std::swap calls it once.
class Event {
public:
Event(): myTime(0.0), myNode(NULL) {}
Event(fpreal t, Node* n);
Event(Event&& other);
Event(Ev... | Your code has two potential locations for where one may expect the move constructor to get called (but it doesn't):
1) calling std::move
2) during assignment.
Regarding 1), std::move does a simple cast - it does not create an object from a copy - if it did then the move constructor might get invoked by it, but s... |
1,046,876 | 1,046,882 | When is the planned date for C++0x to be released into the wild? | We've been waiting forever to see if it's going to become a full-fledged language, and yet there doesn't seem to be a release of the formal definition. Just committees and discussions and revising.
Does anyone know of a planned deadline for C++0x, or are we going to have to start calling it C++1x?
| Well the committee is currently very busy working on the next revision - every meeting is prefaced by many papers, that are a good indicator of the effort that is going into the new standard: http://www.open-std.org/jtc1/sc22/wg21/
What is a little concerning (but reassuring in the sense that they will not rush publish... |
1,046,930 | 1,046,939 | I cannot compile using template in C++ | I compiled the following cords with g++
#include <iostream>
#include <string>
using namespace std;
template<class T>
class Node<const char*>{
private:
string x_;
Node* next_;
public:
Node (const char* k, Node* next):next_(next),x_(k){}
string data(){return x_;}
Node *get_next(){return next_;}
};
$ g++ -c nod... | You're mixing up declarations and instantiations. When you declare a template, you don't specify a type immediately after its name. Instead, declare it like this:
template<class T>
class Node {
private:
const T x_;
Node *next_;
public:
Node (const T& k, Node *next) : x_(k), next_(next) { }
const T& data(){ret... |
1,047,121 | 1,048,525 | How do I generate GUID under Windows Mobile? | Is there a ready-to-use API (C / C++) in Windows Mobile ecosystem that I could use to generate a GUID? I am looking for simple one-shot API to do this. If there is a need to write a whole algorithm or use some extra 3rd-party modules, I will do away without this.
Background. To display notification to the user I use SH... | You don't need to generate a GUID for SHNOTIFICATIONDATA.
You only set the clsid if you want WM to notify a COM object that implements IshellNotificationCallback interface.
Quote from MSDN:
When loading up the SHNOTIFICATIONDATA
structure, you can specify either the
notification class (clsid), the window
to rece... |
1,047,152 | 1,047,156 | MSVC precompiled headers: Which files need to #include "stdafx.h"? | Does every file need to #include "stdafx.h" when using precompiled headers? Or do only source files need to include it.
EDIT: Also, my precompiled header file #includes a lot of STL headers. But, in my headers, I sometimes have functions that return std::vector or something like that, so I need to #include <vector> any... | Every source file needs to include it before any non-comment line. Headers do not need to include it, as every source file will include it before any other header.
|
1,047,200 | 1,047,226 | Extract RGB values from a AVFrame (FFMPEG) in C++ | I am currently trying to read in video frames by using FFMPEG. The format is PIX_FMT_RGB24; For each frame, the RGB values are all combined together in frame->data[0] (Where frame is of the type AVFrame).
How do I extract the individual R, G and B values for each frame? This is for processing the video. I would think ... | My guess:
int p=x*3+y*frame->linesize[0];
r=frame->data[0][p];
g=frame->data[0][p+1];
b=frame->data[0][p+2];
I might have r, g, and b backwards. And there's a lot of room for speedup.
|
1,047,203 | 1,069,813 | Best bignum library to solve Project Euler problems in C++? | I am still a student, and I find project Euler very fun.
sometimes the question requires calculations that are bigger than primitive types. I know you can implement it but I am too lazy to do this,
So I tried few libraries,
MAPM :: very good performance, but it provides only big floats, with the possibility to check if... | Here are a couple of links regarding GMP and Visual Studio 2008:
GMP Install Help at CodeGuru
GMP Compile Guide at The Edge Of Nowhere (this one looks really thorough)
|
1,047,406 | 1,047,508 | How to find the global function? | I have a function name called setValue, used in many classes. Also, i have a global function by the same name. When i press C-], it goes to arbitrary setValue function. How do i directly jump to the global setValue function? It is really pain to use tnext every time to find if the function global.
| When C-] returns multiple matches you can look up the list with
:ts
Then enter the number to jump to correct definition or dismiss the list.
When ctags does not help ...
You can search for occurances of setValue and then jump to the one that looks like definition.
:vim /setValue/ * <-- greps for setV... |
1,047,407 | 1,047,745 | How to use 16bit heightmaps with Ogre3d and PhysX | I'm using Ogre3D and PhysX.
When I load a terrain from an 8bit height map, it looks normal on Visual Debugger.
Look at first image:
http://img44.imageshack.us/gal.php?g=44927650.jpg
But when I save the height map as a 16bit image, I get what you see on second image.
Here's the code, thats works normal with 8bit PNG:
... | Your pOrigSrc is a uchar, which is 8 bits, so you're not getting the correct offset when you do this:
pSrc = pOrigSrc + column*mPageSize +row;
You can fix this by first grabbing the stride of your image before your loops, something like this:
int imageStride = mImage.getBPP() / 8;
and then multiply your calculated of... |
1,047,513 | 1,047,523 | c++ compilation error | Following code is giving compilation error in visual studio 2009.
#include <iterator>
#include <vector>
template <class T1, class T2 >
class A
{
public:
typename std::vector<std::pair<T1,T2> >::iterator iterator;
std::pair<iterator, bool > foo(const std::pair<T1 ,T2> &value_in);
};
can anyone throw some ligh... | This declares iterator to be a variable (not a type):
typename std::vector<std::pair<T1,T2> >::iterator iterator;
Did you mean this?
typedef typename std::vector<std::pair<T1,T2> >::iterator iterator;
Further information: If you're curious about what typename does, read up about the differences between dependent and ... |
1,047,663 | 1,047,694 | How do I declare template function outside the class declaration | #include <iterator>
#include <map>
#include <vector>
template <class T1, class T2>
class A
{
public:
typedef typename std::vector<std::pair<T1,T2> >::iterator iterator;
std::pair<iterator, bool > foo()
{
iterator aIter;
return std::pair<std::vector<std::pair<T1,T2> >::iterator, bool >(aI... | You are again missing the typename in the return value. The function should be:
template <class T1, class T2>
std::pair<typename std::vector<std::pair<T1,T2> >::iterator, bool > A<T1, T2>::foo()
{
iterator aIter;
return std::pair<std::vector<std::pair<T1,T2> >::iterator, bool >(aIter ,false);
}
|
1,048,218 | 1,048,352 | Select() system call in threads? | I am reading data from multiple serial ports. At present I am using a custom signal handler (by setting sa_handler) to compare and wake threads based on file descriptor information. I was searching for a way out to have individual threads with unique signal handlers, in this regard I found that select system call is to... | The POSIX specification (select) is the place to look for the select definition. I personally recommend poll - it has a better interface and can handle any number of descriptors, rather than a system-defined limit.
If I understand correctly you're waking threads based on the state of certain descriptors. A better way w... |
1,048,749 | 1,048,789 | What is the difference between pointer and array in the following context? | #include <cstring>
int main()
{
char *pName = new char[10];
char dummy[] = "dummy";
strcpy(pName + 0,dummy);//how this is different from -->this works
strcpy(pName[0],dummy);//this one...--> error C2664: 'strcpy' :
//cannot convert parameter 1
... |
pName[0] is the first element in a character array (one character)
pName is a shortcut to &pName[0] (a pointer to the first element of your array)
The reason you are getting your error is because strcpy expects a pointer to a char (char*), and not a char value (which is what pName[0] is)
|
1,048,764 | 1,059,901 | validate xml schema using msxml parser | I want to validate an XML file against an XML Schema file. It is a simple xml file, does not include namespace etc. I want to do this in c++, using MSXML 6.0.
| You can validate as you load. This is sample code from the Windows/MSXML SDK:
IXMLDOMSchemaCollectionPtr pXS;
IXMLDOMDocument2Ptr pXD = NULL;
IXMLDOMParseErrorPtr pErr = NULL;
_bstr_t strResult = "";
HRESULT hr = pXS.CreateInstance(__uuidof(XMLSchemaCache50));
... |
1,048,806 | 1,048,821 | Implementing a thread-safe, generic stack in C++ on linux | In a recent interview, I was asked to implement a thread safe generic (i.e.template based) stack in C++, on linux machine.
I quickly came up with the following (It may have compilation errors).
I got through. The interviewer probably liked something in this implementation. Maybe the design part :)
Here are a few proble... | Some issues:
I would implement a Locker class to claim & free the mutex using RAII
I would use std::stack
I would make the user of std::stack use the Locker to implement the locking policy - having a stack that locks itself is bad design, as the stack can't know how it is to be used
|
1,048,904 | 4,623,087 | Help for Boost.Statechart bug | Any ideas how to fix this?
using 1.39_0 on ubuntu 8.10 w/g++ 4.3.2
In the following statechart, the phrase "BUGGY" is printed three
times. One would expect the event would only trigger one "BUGGY". In
the case of the project I am working on, I cannot return
discard_event() as I need the event to reach multiple states (... | Move the reaction you want down to a child state of the top state. This takes it out of the line of forward_state events. I didn't implement it as a inner-type, but you could.
#include <boost/intrusive_ptr.hpp>
#include <boost/mpl/list.hpp>
#include <boost/statechart/custom_reaction.hpp>
#include <boost/statech... |
1,048,968 | 1,049,042 | Reading from a file not line-by-line | Assigning a QTextStream to a QFile and reading it line-by-line is easy and works fine, but I wonder if the performance can be inreased by first storing the file in memory and then processing it line-by-line.
Using FileMon from sysinternals, I've encountered that the file is read in chunks of 16KB and since the files I... | QTextStream has a ReadAll function:
http://doc.qt.io/qt-4.8/qtextstream.html#readAll
Surely that's all you need?
Or you could read all into the QByteArray and QTextStream can take that as an input instead of a QFile.
|
1,049,212 | 1,049,232 | C++ How to read in objects with a given offset? | Now I have a file with many data in it.
And I know the data I need begins at position (long)x and has a given size sizeof(y)
How can I get this data?
| Use the seek method:
ifstream strm;
strm.open ( ... );
strm.seekg (x);
strm.read (buffer, y);
|
1,049,637 | 1,050,938 | Register hotkeys in Linux using library for c++ | are there any libraries for Linux wrote with C++, that could register global hotkeys for my application? Thanks.
| You'll have to provide more information.
In Gnome, the global functionality varies by window manager. Metacity has configurable global shortcuts, as do Compiz and Sawfish, and they're all configured differently. Xhotkeys can also be used for the same functionality. However, these are all limited to starting applica... |
1,049,734 | 1,050,065 | Detecting when an object is passed to a new thread in C++? | I have an object for which I'd like to track the number of threads that reference it. In general, when any method on the object is called I can check a thread local boolean value to determine whether the count has been updated for the current thread. But this doesn't help me if the user say, uses boost::bind to bind my... | In general, this is hard. The question of "who has a reference to me?" is not generally solvable in C++. It may be worth looking at the bigger picture of the specific problem(s) you are trying to solve, and seeing if there is a better way.
There are a few things I can come up with that can get you partway there, but ... |
1,049,853 | 1,051,609 | Net-SNMP variables using C++ | I am having trouble with a few of the variables that the Net-SNMP library provides, specifically the ability to capture in/out Octets.
In/OutOctets Issue: I have another check for ASN_INTEGER and I am catching this oid put the output does not seem to be correct. I am using *vars->val.integer and pushing this into a lon... | I have partially resolved this issue by using ASN_COUNTER instead of ASN_INTEGER. Although a counter32 is in fact an integer it is a type of ASN_COUNTER. So using a check of ASN_COUNTER with *vars->val.integer is in fact the correct method to catch a counter32.
|
1,049,909 | 1,057,277 | VC++ doesn't detect newly created env variable using GetEnvironmentVariable | I'm using the Win32 function GetEnvironmentVariable to retrieve the value of a variable that I just created. I'm running Windows XP and VC++ 2005. If I run the program from within Visual Studio, it can't find the new variable. If I run it from a command-prompt, it does. I restarted VC++ but same result. I even restarte... | Thanks for all the responses. As I mentioned in my question, I tried restarting everything, short of rebooting the PC. It turns out that because my environment variable was a SYSTEM variable, VS doesn't recognize it without rebooting the PC. When I moved the env variable from SYSTEM to USER and restarted VS, it worked ... |
1,049,976 | 1,049,999 | How could this simple pointer equality test fail? | void FileManager::CloseFile(File * const file)
{
for (int i = 0; i < MAX_OPEN_FILES; ++i)
{
if ((_openFiles[i] == file) == true)
{
_openFiles[i] == NULL;
}
}
...
_openFiles is a private member of FileManager and is just an array of File *'s
When the exact same test is pe... | You have
_openFiles[i] == NULL;
should that be
_openFiles[i] = NULL;
?
|
1,050,325 | 1,111,812 | What does the construct keyword do when added to a method? | The code here is X++. I know very little about it, though I am familiar with C#. MS says its similiar to C++ and C# in syntax.
Anyway, I assume the code below is a method. It has "Construct" as a keyword.
What is a construct/Constructor method? What does the construct keyword change when applied to the function?
Als... | Construct is not a keyword in X++, this is merely a static method called construct that returns an InventMovement class. It is used to allow you to create a derived class of a base class without having to know which derived class to create. This is how AX implements the Factory pattern. You will see this pattern used i... |
1,050,377 | 1,050,569 | Machine ID for Mac OS? | I need to calculate a machine id for computers running MacOS, but I don't know where to retrieve the informations - stuff like HDD serial numbers etc. The main requirement for my particular application is that the user mustn't be able to spoof it. Before you start laughing, I know that's far fetched, but at the very ... | Erik's suggestion of system_profiler (and its underlying, but undocumented SystemProfiler.framework) is your best hope. Your underlying requirement is not possible, and any solution without hardware support will be pretty quickly hackable. But you can build a reasonable level of obfuscation using system_profiler and/or... |
1,050,431 | 1,060,283 | What is #nomacros (EP003), and is it alive? | The Evolution WG Issues List of 14 February 2004 has ...
EP003. #nomacros. See EI001. Note by
Stroustrup to be written.
In rough (or exact) terms, what is #nomacros, and is it available as an extension anywhere? It would have been a useful diagnostic tool in a recent project involving porting thousands of files of... | It is just a proposal under active consideration for inclusion into C++, but still not available in the current compilers. If you read further down the page, it says:
ES042. #nospam.
Provide a preprocessor mechanism for limiting macros entering and exiting a scope. For example:
#nomacros
#in A B
…
#out A X
#endnomacros... |
1,050,516 | 1,063,811 | QTabBar icon position | Is there a way to change the alignment of the icon or text of a tab in Qt? Specifically, I would like the text to appear below the icon. By default the icon sits to the left of the text, but that's not appropriate for all situations (especially when you start styling your tabs with stylesheets) It would seem very odd t... | The only way I can see is to create a subclass of QTabBar that implements your own painting algorithm. Then you'd need to subclass QTabWidget to set your own version of the tab bar. It doesn't look like a lot of fun to me.
|
1,050,520 | 1,050,819 | What is LogonUser()'s token returned used for? | What can you do with the token LogonUser returns? And what is it used for?
BOOL LogonUser(
__in LPTSTR lpszUsername,
__in_opt LPTSTR lpszDomain,
__in LPTSTR lpszPassword,
__in DWORD dwLogonType,
__in DWORD dwLogonProvider,
__out PHANDLE Token
);
I just need a more general discripti... | As MSDN says: "In most cases, the returned handle is a primary token that you can use in calls to the CreateProcessAsUser function". There are no reasons not to believe.
Sample: you could write your own runas.exe. Call LogonUser with username&password from command line. Then call CreateProcessAsUser to start program wi... |
1,051,010 | 1,051,044 | How to take a pointer to a template function specialized on a string? | I was trying use a set of filter functions to run the appropriate routine, based on a string input. I tried to create matcher functions for common cases using templates, but I get a "type not equal to type" error when I try to store a pointer to the specialized function (in a structure, in the real application)
Distil... | Strings as template-value parameters are prohibited by the ISO standard.
|
1,051,035 | 7,739,683 | DirectShow stop/resume live stream | I'm using DirectShow to play audio/video files in my application. I use IGraphBuilder::RenderFile() to build the filter graph and the IMediaControl interface to play/pause/stop the media. This works fine for local media files, but causes problems with live mms streams.
If I call IMediaControl::Stop() on a live stream, ... | The behavior indicates that one of the filters in the graph exhibits buggy behavior. The filter has to be replaced if you want to be able to re-run the feed. Also there is no good source filter to render mms:// streams which are obsolete themselves as protocol. Windows Media Player in Windows 7 is using its private Dir... |
1,051,089 | 1,051,209 | Managing Implicit Type Conversion in C++ | I'm working on code that does nearest-neighbor queries. There are two simple ideas that underlie how a user might query for data in a search:
closest N points to a given point in space.
all points within a given distance.
In my code, Points are put into a PointList, and the PointList is a container has the job of kee... | Overload resolution for integer types happen on two categories, which can be very roughly summarized to
Promotion: This is a conversion from types smaller than int to int or unsigned int, depending on whether int can store all the values of the source type.
Conversion: This is a conversion from any integer type to a... |
1,051,474 | 1,060,351 | Make a window Static as well as allow adding text using CreateWIndowEx() | I'm using CreateWindowEx() function to create an "EDIT" window, i.e. where a user can type.
g_hwndMain = CreateWindowEx(0,
WC_TEXT,
NULL,
WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL,
0, 0, 400, 200,
... | Thanks for your help. Ok So far I've done this to handle WM_WINDOWPOSCHANGING message
BOOL OnWindowPosChanging(HWND hwnd, WINDOWPOS *pwp)
{
return 0;
}
LRESULT CALLBACK
WndProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
switch (uiMsg) {
HANDLE_MSG(hwnd, WM_WINDOWPOSCHANGING, OnWindowPosC... |
1,051,480 | 1,051,535 | VS 2008 C++ how to make a project without .net dependency | I am writing a plain vanilla c++ console app using VS 2008. When I create the project, the IDE gives me a choice of .net versions. There is no option for 'none'. When I look at the project properties page, the Targeted Framework has whatever value I chose and is greyed out.
When I try and run the app on a windows machi... | Make sure that you chose the "Win32 Console Application" project type. This will give you a C++ only project. Most of the other console options will bind the project to .Net.
|
1,051,539 | 1,051,564 | Pre/Post function call implementation | I was wondering if I could do pre/post function call in C++ somehow. I have a wrapper class with lots of functions, and after every wrapper function call I should call another always the same function.
So I do not want to put that postFunction() call to every single one of the functions like this:
class Foo {
f1();... | Might be a case for RAII! Dun-dun-dunnn!
struct f1 {
f1(Foo& foo) : foo(foo) {} // pre-function, if you need it
void operator()(){} // main function
~f1() {} // post-function
private:
Foo& foo;
}
Then you just have to make sure to create a new temporary f1 object every time you wish to call the function. Reus... |
1,051,597 | 1,051,644 | Is there a "function size profiler" out there? | After three years working on a C++ project, the executable has grown to 4 MB. I'd like to see where all this space is going. Is there a tool that could report what the biggest space hogs are? It would be nice to see the size by class (all functions in a class), by template (all instantiations), and by library (how much... | In Linux, you can use nm to show all symbols in the executable and to sort them in reverse order by size:
$ nm -CSr --size-sort <exe>
Options:
-C demangles C++ names.
-S shows size of symbols.
--size-sort sorts symbols by size.
-r reverses the sort.
If you want to get the results per namespace or per class, you can ... |
1,051,611 | 1,059,801 | Why do I get a "member function not present" error when evaluating expressions on the VC++ debugger? | I've got a static method, MyClass::myMethod() on another DLL, MyDll.dll. In my code, I call this method, and it compiles and runs fine.
But when I try MyClass::myMethod() in the immediate window (or the watch window), I always get:
MyClass::myMethod()
CXX0052: Error: member function not present
Why is that?
Update: I'... | Well, I'm not sure why, but the debugger isn't smart enough to know that class is in another DLL, so you have to explictly tell it by using the context operator:
{,,MyDLL}MyClass::myMethod()
|
1,051,618 | 1,051,671 | C++ Casting a byte binary value into a string | How do I convert 6 bytes representing a MAC address into a string that displays the address as colon-separated hex values?
Thanks
| You probably want a sequence of six bytes to be formatted like so:
aa:bb:cc:dd:ee:ff
where aa is the first byte formatted in hex.
Something like this should do:
char MAC[6]; //< I am assuming this has real content
std::ostringstream ss;
for (int i=0; i<6; ++i) {
if (i != 0) ss << ':';
ss.width(2); //< Use two... |
1,051,667 | 1,051,698 | VC++: How to get the time and date of a file? | How do I get the file size and date stamp of a file on Windows in C++, given its path?
| You can use FindFirstFile() to get them both at once, without having to open it (which is required by GetFileSize() and GetInformationByHandle()). It's a bit laborious, however, so a little wrapper is helpful
bool get_file_information(LPCTSTR path, WIN32_FIND_DATA* data)
{
HANDLE h = FindFirstFile(path, &data);
if(... |
1,052,102 | 1,052,131 | Template instantiation error | I have template function "compare" defined as below.
#include<iostream>
using namespace std;
template<typename T>
void compare(const T&a, const T& b)
{
cout<<"Inside compare"<<endl;
}
main()
{
compare("aa","bb");
compare("aa","bbbb");
}
When i instantiate compare with string literals of same length, the compiler... | As stated in Greg's answer and comments, the two different array types (since that's what string literals are) is the problem. You may want to leave the function as-is for generic types, but overload it for character pointers and arrays, this is mostly useful when you want to treat them slightly differently.
void compa... |
1,052,168 | 1,052,197 | Thread-safe static variables without mutexing? | I remember reading that static variables declared inside methods is not thread-safe. (See What about the Meyer's singleton? as mentioned by Todd Gardner)
Dog* MyClass::BadMethod()
{
static Dog dog("Lassie");
return &dog;
}
My library generates C++ code for end-users to compile as part of their application. The cod... | You are correct that static initialization like that isn't thread safe (here is an article discussing what the compiler will turn it into)
At the moment, there's no standard, thread safe, portable way to initialize static singletons. Double checked locking can be used, but you need potentially non-portable threading li... |
1,052,411 | 1,052,436 | running ping with Qprocess, exit code always 2 if host reachable or not | i am using Qprocess to execute ping to check for a host to be online or not...
The problem is that the exit code that i recieve from the Qprocess->finished signal is always 2 no matter if i ping a reachable host or an unreachable one..
I am continuously pinging in a QTimer to a host(whose one folder i have mounted at c... | I think it's a bad practice to rely on ping.exe exit code as it's undocumented. Furthermore it's been known that in different versions of Windows the exit code is inconsistent.
You could:
implement your own ping. there are plenty free implementations out there such as this (first one when searching "ping.c" in google)... |
1,052,458 | 1,052,493 | Defining a proper subtraction operator | I wrote an abstraction class for a math object, and defined all of the operators. While using it, I came across:
Fixed f1 = 5.0f - f3;
I have only two subtraction operators defined:
inline const Fixed operator - () const;
inline const Fixed operator - (float f) const;
I get what is wrong here - addition is swappable... | If you need reassuring that friend functions can be OK:
http://www.gotw.ca/gotw/084.htm
Which operations need access to
internal data we would otherwise have
to grant via friendship? These should
normally be members. (There are some
rare exceptions such as operations
needing conversions on their left-hand
... |
1,052,489 | 1,052,500 | A Unique and Constant Identifier for a pthreads thread? | I presumed that a pthread_t remains constant - for a given thread - for its entire life, but my experimentation seems to be proving this assumption false. If the id for a given thread does not remain constant across its life, how can I store a pthread_t so another thread can use pthread_join to block until the thread i... | You cannot rely on a pthread_t being unique, but you can use pthread_equal() to determine whether two thread ids refer to the same thread.
NAME
pthread_equal -- compare thread IDs
SYNOPSIS
#include <pthread.h>
int
pthread_equal(pthread_t t1, pthread_t t2);
DESCRIPTION
The pthread_equal() fun... |
1,052,492 | 1,052,501 | Calling inline functions C++ | I have an inline member function defined under class MyClass
int MyClass::myInlineFunction();
This function is called from several places in my code.
There are two ways to call this function
Case 1: Using this every time the function is called.
mobj->myInlineFunction() ;
Case 2: Assign the result of this function ... | Case 2 can give you a lot of performance, if the function does something that takes some time.
Choose it if
you do not need side effects of the function to happen
the function would always the return the same result in that context
|
1,052,620 | 1,052,648 | Checking if number is even by looking at the last bit - are there any other "tricks" like this one? | Recently I discovered, that if I need to see if variable is even ( or odd ), I could just see if last bit of variable equals 0. This discovery, when implemented, replaced few modulo 2 calculations and thus, whole function ran faster.
Are there any other "tricks" like this one, where working with bits could replace othe... | I doubt that replacing the use of modulo-two calculations by the equivalent bitwise operation produced faster execution times. Any C++ compiler worth its grain of salt will compile n % 2 and n & 1 to identical machine instructions.
Beware of using bit-twiddling hacks as an optimization. First, it's not always clear tha... |
1,052,629 | 1,052,656 | How Program Becomes a Process. How OS makes Program a process | I wanted to know How OS actually makes a program in to process. what are steps Os engages to make program a process.
I mean How a Program becomes a Process, what are the parameter OS adds to kernel datastructure before making a program a process
Thank you in advance.
| Every operating system is going to do this in a different manner.
However, in general the following steps will occur in a modern operating system:
New address space created
Program image loaded into an agreed upon address
This may involve relocation of the image, or a dependency.
Execution "context" setup
Include... |
1,052,691 | 2,980,795 | Trouble with QxtGlobalShortcut | I'm trying to set global shortcut for my applcation using QxtGlobalShortcut.
Here is my code:
QxtGlobalShortcut m_hotkeyHandle;
m_hotkeyHandle.setShortcut( QKeySequence("Ctrl+Shift+X") );
m_hotkeyHandle.setEnabled(true);
connect( &m_hotkeyHandle, SIGNAL(activated()),
this, SLOT(hotkeyPressed()) );
void MainW... | There was a bug in Qxt-lib 0.5 with shortcut. I spoke with developer and knew that i just need to update library from dev-branch (0.5.1 is worked).
|
1,052,727 | 1,052,737 | Thread safe singleton implementation in C++ | The following is a well known implementation of singleton pattern in C++.
However, I'm not entirely sure whether its thread-safe.
Based upon answers to similar question asked here previously, it seems it is thread safe.
Is that so?
//Curiously Recurring Template Pattern
//Separates a class from its Singleton-ness... | No, this is not thread safe because the static local is not guarded in any way. By default a static local is not thread safe. This means you could run into the following issues
Constructor for the singleton runs more than once
The assignment to the static is not guaranteed to be atomic hence you could see a partial ... |
1,052,805 | 1,052,986 | Programatically get the web page content | I would like to know whether WinInet or WinHttp will get webpage contents quickly or is there any other quicker method for getting webpage content (less than 1 sec).
The programming environment which I am using is VC++
| As said by the commenters, Internet doesn't guarantee load times.
As for the specific API, I'd use XMLHTTPRequest COM object instead of WinInet or WinHttp.
P.S. Don't forget to call CoInitialize.
|
1,052,992 | 1,055,628 | KeyboardProc returning TRUE causes performance drops | I'm developing an interface for an add-on to a game. I can't use the game API (for several reasons including the fact that the code must be game-agnostic) and I need to get keyboard input from the user so I've decided to use a keyboard hook (WH_KEYBOARD) to process user input when certain conditions are met.
The proble... | As much as I don't like answering my own question I've found the cause of the delay. The message pump of the games I've tested my code against was implemented with a while(PeekMessage) { GetMessage... } and removing the keyboard input message somehow caused GetMessage to block for sometime. Using PostMessage and WM_NUL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.