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,334,069 | 1,334,112 | Are const arrays declared within a function stored on the stack? | if this was declared within a function, would it be declared on the stack?
(it being const is what makes me wonder)
void someFunction()
{
const unsigned int actions[8] =
{ e1,
e2,
etc...
};
}
| Yes, they're on the stack. You can see this by looking at this code snippet: it will have to print the destruction message 5 times.
struct A { ~A(){ printf( "A destructed\n" ); } };
int main() {
{
const A anarray [5] = {A()} ;
}
printf( "inner scope closed\n");
}
|
1,334,284 | 1,334,319 | Debugging Visual Studio builds from Eclipse | I'm just starting out on a cross-platform (Windows, Linux, OS X) C++ project, and we've decided to use Scons for our build system and Eclipse as our IDE. I've figured out how to trigger Scons to do a Visual C++ build from Eclipse, and for errors etc. to get reflected in Eclipse, so all good so far. However, what would ... | Visual C++ creates PDB files for its own symbols that map into the binary. The only provision for other debuggers is to C7 format and hope that is enough for gdb.
Go to Properties | C/C++ | General | Debug Information = C7 Compatible (instead of the default PDB). Command line is /Z7 instead of other /Z? (which can be... |
1,334,582 | 1,334,635 | Where to find a description of all the math functions like floorf and others? | math.h is not really a documentation. Is there something else that will describe these functions a but more in detail?
| floorf() is a variant for the floor() function, accepting and returning float values instead of double.
The GNU Libc documentation is very helpful.
The iPhone documentation also has a man page about floor() functions.
|
1,334,596 | 1,334,644 | C++ vs C# for GUI programming | I am going to program a GUI under windows (will be about 10,000 line code with my estimates) and don't know C# or C++ (QT library) to choose for my needs. Please help me to choose.
| If you have to debate on using C# or C++ then the correct answer is probably C#. I would stay away from a low level language like C++ unless you absolutely have to as the amount of time required to develop/debug with it will be much greater. C# has a lot of GUI functionality that it harnesses from the .NET framework. T... |
1,334,858 | 6,952,193 | Why don't iostream objects overload operator bool? | In this answer I talk about using a std::ifstream object's conversion to bool to test whether the stream is still in a good state. I looked in the Josuttis book for more information (p. 600 if you're interested), and it turns out that the iostream objects actually overload operator void*. It returns a null pointer wh... | This is an instance of the "safe bool" problem.
Here is a good article: http://www.artima.com/cppsource/safebool.html .
C++0x helps the situation with explicit conversion functions, as well as the change that Kristo mentions. See also Is the safe-bool idiom obsolete in C++11? .
|
1,334,989 | 1,337,988 | Debugging data in 'anonymous namespaces' (C++) | Recently, I got a crash dump file from a customer. I could track the problem down to a class that could contain incorrect data, but I only got a void-pointer to the class, not a real pointer (void-pointer came from a window-property, therefore it was a void-pointer).
Unfortunately, the class to which I wanted to cast ... | This is mentioned in MSDN. It doesn't look like there's a nice solution within the Watch window (you can get the decorated name of your class from a listing I guess).
Your "silly-named namespace" idea would work okay, you could also just declare an identical class with a silly name and cast to that type instead.
|
1,335,040 | 1,335,112 | Boost linking, Visual Studio & version control | I'm using Visual Studio 2008, and writing some stuff in C++. I'm using a Boost library (that is not header only).
So, linking to Boost requires one to add the directory to Boost binaries to the project's "additional linker paths" setting.
However, doesn't this conflict with source control? If I check in the project fil... | Adding the Boost paths to "Visual C++ Directories" should work.
You should add include path <Full path here>\boost_1_39_0 (no boost at the end)
and library path <Full path here>\boost_1_39_0\bin.v2\lib (bin.v2 is a stage dir that could be different in you case).
Personally, I store boost sources in my source control an... |
1,335,052 | 1,338,991 | c++, syntax for passing parameters | This code snippet is part of an isapi redirect filter written in managed c++ that will capture url requests with prefix "http://test/. Once the url is captured it will redirect those request to a test.aspx file i have at the root of my web app.
I need some syntax help how to:
1) pass the "urlString" parameter to be di... | The CString::Replace method takes the string-to-be-replaced and the string-to-be-put-in-place as arguments. s.Replace( "foo", "bar" ) will convert "tadafoo" into "tadabar".
Now your code will replace "anystring" with "/test.aspx?urlString". Literally.
My guess is that you want your url to be appended to the "/text.as... |
1,335,137 | 1,335,202 | Using STL to bind multiple function arguments | In the past I've used the bind1st and bind2nd functions in order to do straight forward operations on STL containers. I now have a container of MyBase class pointers that are for simplicities sake the following:
class X
{
public:
std::string getName() const;
};
I want to call the following static function using... | A reliable fallback when the bind-syntax gets too weird is to define your own functor:
struct callDoSomething {
void operator()(const X* x){
StaticFuncClass::doSomething(x->getName(), funcReturningString());
}
};
for_each(ctr.begin(), ctr.end(), callDoSomething());
This is more or less what the bind functions... |
1,335,301 | 1,336,533 | Using boost::bind with a constructor | I'm trying to create new objects and add them to a list of objects using boost::bind. For example.
struct Stuff {int some_member;};
struct Object{
Object(int n);
};
....
list<Stuff> a;
list<Object> objs;
....
transform(a.begin(),a.end(),back_inserter(objs),
boost::bind(Object,
boost::bind(&Stuff::some_m... | If Stuff::some_member is int and Object has a non-explicit ctor taking an int, this should work:
list<Stuff> a;
list<Object> objs;
transform(a.begin(),a.end(),back_inserter(objs),
boost::bind(&Stuff::some_member,_1)
);
Otherwise, you could use boost::lambda::constructor
|
1,335,590 | 1,335,610 | Removing duplicate string from List (.NET 2.0!) | I'm having issues finding the most efficient way to remove duplicates from a list of strings (List).
My current implementation is a dual foreach loop checking the instance count of each object being only 1, otherwise removing the second.
I know there are MANY other questions out there, but they all the best solutions... | This probably isn't what you're looking for, but if you have control over this, the most efficient way would be to not add them in the first place...
Do you have control over this? If so, all you'd need to do is a myList.Contains(currentItem) call before you add the item and you're set
|
1,335,965 | 1,336,246 | Howto make Java JNI KeyListener with C++ | I'm trying to make a program like AutoHotKey, but with a graphical interface.
I'm using java.awt.Robot
Now I want to make the code for checking the state from a key (In AHK: getKeyState)
Of course somthing like a KeyListener without having focus.
I read already something with JNI and C++, but....
I can't find some info... | There are lot of good JNI resources for starting out with JNI Programming like the Sun JNI Tutorial. Almost all Tutorials assume a good knowledge of C/C++ because the Java Native Interface (JNI) is the bridge between native C/C++ code, the Java Virtual Machine and everything running in there (meaning your Java Bytecode... |
1,336,426 | 1,336,509 | FindFirstFile and FindNextFile question | Output:
The first file found is LOG_09.TXT
Next file name is LOG_10.TXT
Next file name is LOG_11.TXT
Next fi (cut off word "file"?)
Function:
//Find last modified log file
hFind = FindFirstFile("..\\..\\LOGS\\LOG*.TXT", &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
p... | Since your app is multithreaded, the printf may get cut short half way through, by another thread which then gets control, try this:
After all printf() calls, use fflush(stdout);, to make sure that the buffer is flushed.
If that doesn't fix it you can protect the stdout resource with a named mutex, or a critical secti... |
1,336,476 | 1,336,609 | Stack Frame Question: Java vs C++ | Q1. In Java, all objects, arrays and class variables are stored on the heap? Is the same true for C++? Is data segment a part of Heap?
What about the following code in C++?
class MyClass{
private:
static int counter;
static int number;
};
MyClass::number = 100;
Q2. As far as my understand... | This is somewhat simplified but mostly accurate to the best of my knowledge.
In Java, all objects are allocated on the heap (including all your member variables). Most other stuff (parameters) are references, and the references themselves are stored on the stack along with native types (ints, longs, etc) except string... |
1,336,561 | 1,337,408 | Change resize behavior in Qt layouts | I want my custom widgets to gain extra space when the dialog is resized. This was working when I only had a handful of widgets, but after adding several more columns of these same widgets and putting them in a QGridLayout, the extra space merely goes in as padding between the widgets.
| I've had trouble with this in the past and here are some of the things I've found:
First make sure all the widgets you want to expand have sizePolicy set to "Expanding".
Make sure the widgets that make up your custom widgets are in a layout that allows for expanding. You can check this by just adding one of your cust... |
1,336,688 | 1,336,700 | Looking for an application GUI library for C++ | I'm thinking about writing a very simple paint program. I would like a more advanced method of inputting data into my program like colors, thickness of the brush, etc. I would like to use a GUI library so I can program buttons and menus to make input easier.
Any suggestions?
(I'm running Visual C++ 2005 SP1)
| Qt is a pretty solid GUI application framework. It is cross-platform, well documented, supported, and free.
|
1,336,895 | 1,337,671 | boost::bind, boost::asio, boost::thread, and classes | sau_timer::sau_timer(int secs, timerparam f) : strnd(io),
t(io, boost::posix_time::seconds(secs))
{
assert(secs > 0);
this->f = f;
//t.async_wait(boost::bind(&sau_timer::exec, this, _1));
t.async_wait(strnd.wrap(boost::bind(&sau_timer::exec, this)));
boost::thread thrd(&io,this);
io.run();... | The explanation is at the end of the error messages:
c:\users\ben\documents\visual studio 2008\projects\sauria\sauria\sau_timer.cpp(11) :
see reference to function template instantiation
'boost::thread::thread<boost::asio::io_service*,sau_timer*>(F,A1)' being compiled
The error occurs while generating the ctor of... |
1,336,950 | 1,337,020 | Call Tiny C Compiler from a C++ code | I'm trying to compile a C code in a file from a program in C++. When I run my program it call the Tiny C Compiler and generate a dll from the compilation of c code.
I tried to do it by a lot of ways but I couldn't. Did anyone already do something like this?
Thanks
| What platform are you on?
On most platforms, you can use the C standard library's system() function to launch a separate process from your C++ program.
#include <stdlib.h>
int main (int argc, char *argv[])
{
system ("tcc -o myproc a.c");
return 0;
}
This will block until the spawned process exits.
On Windows, i... |
1,337,210 | 1,337,265 | Programs run in 2 seconds on my machine but 15 seconds on others | I have two programs written in C++ that use Winsock. They both accept TCP connections and one sends data the other receives data. They are compiled in Visual Studio 2008. I also have a program written in C# that connects to both C++ programs and forwards the packets it receives from one and sends them to the other. In ... | You should profile your application on the good, 2 second case, and the 15 second lab case and see where they differ. The difference could be due to any number of a problems (disk, antivirus, network) - without any data backing it up we'd just be shooting in the dark.
If you don't have access to a profiler, you can ad... |
1,337,470 | 1,337,487 | Type limitation in loop variables in Java, C and C++ | Why Java, C and C++ (maybe other languages also) do not allow more than one type on for-loop variables? For example:
for (int i = 0; i < 15; i++)
in this case we have a loop variable i, which is the loop counter.
But I may want to have another variable which scope is limited to the loop, not to each iteration. For exa... | This limitation exists because your requirement is fairly unusual, and can be gained with a very similar (and only slightly more verbose) construct. Java supports anonymous code blocks to restrict scope if you really want to do this:
public void method(int a) {
int outerVar = 4;
{
long variable = obj.operation... |
1,337,517 | 1,337,692 | Debugging/tracing inside a shared library during runtime? | I'm trying to understand how a certain library works. I've compiled it with my added prinfts and everything is great. Now I want to stop the example program during runtime to look at the call stack, but I can't quite figure out how to do it with gdb. The function I want to break on, is inside a shared library. I've rev... | You can do "break main" first. By the time you hit that, the shared library should be loaded, and you can then set a breakpoint in any of its routines.
|
1,337,523 | 56,544,100 | Measuring text width in Qt | Using the Qt framework, how do I measure the width (in pixels) of a piece of text rendered with a given font/style?
| Since Qt 5.11 you must use horizontalAdvance() method of QFontMetrics class instead of width(). width() is now obselete.
QFont myFont(fontName, fontSize);;
QString str("I wonder how wide this is?");
QFontMetrics fm(myFont);
int width=fm.horizontalAdvance(str);
|
1,337,529 | 1,337,546 | How to update a printed message in terminal without reprinting | I want to make a progress bar for my terminal application that would work something like:
[XXXXXXX ]
which would give a visual indication of how much time there is left before the process completes.
I know I can do something like printing more and more X's by adding them to the string and then simply printf, ... | try using \r instead of \n when printing the new "version".
for(int i=0;i<=100;++i) printf("\r[%3d%%]",i);
printf("\n");
|
1,337,722 | 1,337,886 | How to place objects that seem not be comparable in a C++ std::set? | Suppose I want to put objects that identify a server into a stl set. Then I would have to make sure that I also implement operator< for these objects otherwise I would run into a compiler error:
struct ServerID
{
std::string name; // name of the server
int port;
};
std::set<ServerID> servers; // compiler error, no... | I would recommend not implementing it as operator<, to avoid possible confusion, but rather pass the order function as a parameter to the std::set template argument.
struct server
{
std::string name;
int port;
};
struct name_then_port : public std::binary_function<server,server,bool>
{
bool operator()( server ... |
1,337,923 | 1,337,959 | Authenticating users using Active Directory in Client-Server Application | I've been asked to provide support for authenticating users against an Active Directory in our existing client server application.
At the moment a user supplies a user name and password from a client machine, passed over the wire (encrypted) to our server process and matched against a user name/password stored in a d... | You do an NTLM/Kerberos/Negotiate SSPI exchange loop. There is a a full sample on MSDN for both the client and the server. To be clear: you do not use any sort of LDAP access explictily. Is the LSA (Local Security Authority) that talks with LDAP and establishes the identity of the client. If you are succesful in doing ... |
1,337,938 | 1,337,991 | What are some reasons not to statically link to the VC CRT? | I'm finding that with dynamic linking, even with SxS, Windows Update will come along and stomp on a version of the VC8 CRT (for example it has a security flaw) and then my app will fail to run with older versions.
What are some of the important reasons to stay with the dynamic linking with VC CRT, other than increasing... |
Staying up to date on security fixes is a good reason. Otherwise, you're responsible for rebuilding your application with a fixed CRT and deploying it to your customers.
Using a shared CRT should result in lower memory footprint for the system, since most of the DLL's pages can be shared between processes.
|
1,338,179 | 1,338,188 | How to take these parameters the same way this function does? | For example:
- (BOOL)compare:(NSDecimal)leftOperand greaterThan:(NSDecimal)rightOperand {
NSComparisonResult result = NSDecimalCompare(&leftOperand, &rightOperand);
// rest not important
}
like you can see, the method just receives these two types of NSDecimal, leftOperand and rightOperand. Then it passes them... | Try:
- (BOOL)compare:(const NSDecimal*)leftOperand greaterThan:(const NSDecimal*)rightOperand {
NSComparisonResult result = NSDecimalCompare(leftOperand, rightOperand);
// rest not important
}
|
1,338,436 | 1,338,467 | How to initial static member in C++ using function | I am using C++.
in .h:
static CRITICAL_SECTION g_CS;
in .cpp:
CRITICAL_SECTION CQCommon::g_CS;
but I want to use
QGUID temp;
EnterCriticalSection(&g_CS);
temp = g_GUID++;
LeaveCriticalSection(&g_CS);
return temp;
in one static function.
How can I invoke InitializeCriticalSection(PCRITICAL_SECTION pcs);?
Can I using ... | If you want a different approach you can create an object to manage it:
class CriticalSectionManager
{
public:
CriticalSectionManager()
{
InitializeCriticalSection(&g_CS);
}
~CriticalSectionManager()
{
DeleteCriticalSection(&g_CS);
}
};
void Func(void)
{
static CriticalSectionManager man;
//... |
1,338,645 | 1,344,934 | TokyoCabinet: Segmentation fault at hdb->close() | I'm stuck at a Segmentation fault after inserting about 8 million records in a TC Hash Database. After everything is inserted I close the DB but I caught a Segmentation Fault at this part of the code (tchdb.c):
static void tchdbsetflag(TCHDB *hdb, int flag, bool sign){
assert(hdb);
char *fp = (char *)hdb->map + HDB... | Just solved the problem.
I'm on a 32bits system and TC can only handle databases up to 2GB in such systems.
The solution is building TC with the "--enable-off64" option. Something like this:
./configure --enable-off64
make
make install
|
1,338,742 | 1,338,783 | Initialize a pointer to a class with NULL values | I am tring to intialize an array of pointers to a NODE struct that I made
struct Node{
int data;
Node* next;
};
the private member of my other class is declared as
Node** buckets;
It is currently initialised as
buckets = new Node*[SIZE]
Is there anyway to initialize the array so that its members point to... | First of all, the simplest solution is to do the following:
Node** buckets = new Node*[SIZE]();
As litb previously stated, this will value initialize SIZE pointers to null pointers.
However, if you want to do something like Node **buckets and initialize all of the pointers to a particular value, then I recommend std:... |
1,338,846 | 1,338,851 | C global static - shared among threads? | In C, declaring a variable static in the global scope makes it a global variable. Is this global variable shared among threads or is it allocated per thread?
Update:
If they are shared among threads, what is an easy way to make globals in a preexisting library unique to a thread/non-shared?
Update2:
Basically, I need t... | It's visible to the entire process, i.e., all threads. Of course, this is in practice. In theory, you couldn't say because threads have nothing to do with the C standard (at least up to c99, which is the standard that was in force when this question was asked).
But all thread libraries I've ever used would have globals... |
1,338,976 | 1,338,984 | Converting integer identifiers to pointers | I have ID values of the type unsigned int. I need to map an Id to a pointer in constant time.
Key Distribution:
ID will have a value in the range of 0 to uint_max. Most of keys will be clustered into a single group, but there will be outliers.
Implementation:
I thought about using the C++ ext hash_map stuff, but I'... | Use a hash map (unordered_map). This gives ~O(1) look-up times. You "heard" it was bad, but did you try it, test it, and determine it to be a problem? If not, use a hash map.
After your code gets close to completion, profile it and determine if the look-up times are the main cause of slowness in your program. Chances ... |
1,339,118 | 1,339,125 | c++ problem with enum and struct | why doesn't this compile:
enum E { a, b}
typedef struct { int i; E e; } S;
int main(){return 0;}
I get different errors on different system.
| You need a semicolon after the enum.
enum E { a, b};
|
1,339,270 | 1,339,327 | How do I prefix the length of message in TCP/IP | I'm sending messages over TCP/IP, I need to prefix message length in a char array and then send it. How do I do it?
Also can you please provide an example of how to extract it at the another end. And if possible, please explain.
I'm using C++ and Winsock.
EDIT:
string writeBuffer = "Hello";
unsigned __int32 length = h... | When sending a length field on a TCP stream, you need to decide two things:
what length should the length have (1 byte, 2 bytes, 4 bytes, variable length)
what endianness should I use
I recommend to use 4 bytes length, and network byte order (i.e. big-endian). For network byte order, the macros htonl and ntohl will c... |
1,339,428 | 1,339,436 | Constant reference to temporary object | Let's say there is a function like
void SendToTheWorld(const Foo& f);
and I need to preprocess Foo object before sending
X PreprocessFoo(const Foo& f)
{
if (something)
{
// create new object (very expensive).
return Foo();
}
// return original object (cannot be copied)
return f;
}
Usage
Fo... | I’m not 100% clear on what you mean but if you just want to omit an unnecessary copy of Foo in the return value, make your function small (right now, it is) and rely on the optimizing compiler to take care of your problem.
Once the function has been inlined, the compiler will elide unnecessary copies of Foo.
(Note for ... |
1,339,470 | 1,339,487 | How to get the address of the std::vector buffer start most elegantly? | I want to use std::vector for dynamically allocating memory. The scenario is:
int neededLength = computeLength(); // some logic here
// this will allocate the buffer
std::vector<TCHAR> buffer( neededLength );
// call a function that accepts TCHAR* and the number of elements
callFunction( &(buffer[0]), buffer.siz... | Well, you can remove one set of parens:
&buffer[0]
but that is the common, idiomatic way of doing it. If it really offends you, I suppose you could use a template - something like:
template <typename T>
T * StartOf( std::vector <T> & v ) {
return &v[0];
}
|
1,339,601 | 1,339,685 | warning: returning reference to temporary | I have a function like this
const string &SomeClass::Foo(int Value)
{
if (Value < 0 or Value > 10)
return "";
else
return SomeClass::StaticMember[i];
}
I get warning: returning reference to temporary. Why is that? I thought the both values the function returns (reference to const char* "" and r... | This is an example when an unwanted implicit conversion takes place. "" is not a std::string, so the compiler tries to find a way to turn it into one. And by using the string( const char* str ) constructor it succeeds in that attempt.
Now a temporary instance of std::string has been created that will be deleted at the ... |
1,339,605 | 1,339,667 | Remote debugging error with eclipse CDT | I am using Galileo CDT on mac os x 10.5.7. I want to remotelly debug a c++ application on a linux machine. I found this guide:
http://www.embedded-linux.co.uk/tutorial/eclipse-rse
But when it comes to the step
"Install Remote System Explorer", when I go to "available software", I only get error messages like "No reposi... |
I only get error messages like "No repository found at http::/downlo" and so.
What is the exact error message?
Do not forget Eclipse has its own HTTP proxy settings. Please check them out. (Preferences / General / Network Connections)
alt text http://help.eclipse.org/stable/topic/org.eclipse.platform.doc.user/whatsNe... |
1,339,922 | 1,340,030 | prevent accidental object copying in C++ | In our company's coding standard, we have been told to "be aware of the ways (accidental) copying can be prevented".
I am not really sure what this means, but assume that they mean we should stop classes from being copied if this is not required.
What I can think of is as follows:
Make the copy constructor of a class ... | If your coding standard states "be aware of the ways (accidental) copying can be prevented", I'm guessing they aren't just talking about preventing copies from within the classes itself, but about the performance implications of unnecessary / accidental copies when using the classes.
One of the main causes of unnecessa... |
1,339,997 | 1,340,124 | Is it possible to use __func__ in gcc 3.3+ the old way? (C++) | With gcc versions before 3.3 and with the MS compiler I use the following macro:
DEBUG_WARNING(...) printf(">WARNING: "__FUNCTION__"() " __VA_ARGS__);
Use:
DEBUG_WARNING("someFunction returned %d", ret);
Output:
>WARNING: Class::FunctionName() someFunction returned -1
Its extremely handy when we have lots of system... | Since __FUNCTION__ and __func__ is a predefined identifier and not a string literal, you cannot use it in preprocessor string literal concatenation. But you can use it in printf formatting. Also note the use of ##args instead of __VA_ARGS__ to use GNU style variadic macro arguments to work around the issue with the com... |
1,340,099 | 1,340,203 | Worker threads stop their work after a moment | I have a serial application that I parallelized using OpenMP. I simply added the following to my main loop :
#pragma omp parallel for default(shared)
for (int i = 0; i < numberOfEmitters; ++i)
{
computeTrajectoryParams* params = new computeTrajectoryParams;
// defining params...
outputs[i] = (int*) ... | It might depend on the scheduling scheme, and the computation size in each cycle.
If the scheduling is static - each thread is assigned with work before it is run. Each thread will get 1/4 of the indexes. It is possible that some threads finish before others because their work is easier than that of other threads (or m... |
1,340,181 | 1,341,039 | Own Object as Data in stl Multimap | I'm writing an application, where I want to store strings as keys ans a custom Object as value
multimap<string, owncreatedobject> mymap;
Compiling does well, but I get a "Segmentation fault" when using the function insert
during runtime.
mymap.insert(string,myobject); --> Segmentation Error
A already added a copycons... | I fiddle with your problem for the last hour and I think I got it.
Try using something in the matter of this code segment:
multimap<string,yourclass const*> mymap
void addtomap(string s,yourclass const* c)
{
mymap.insert(pair<string, yourclass const*>(s,c));
}
...`addtomap("abc",&z);
In your given example you tried... |
1,340,268 | 1,340,289 | What is Microsoft using as the data type for Unicode Strings? | I am in the process of learning C++ and came across an article on the MSDN here:
http://msdn.microsoft.com/en-us/magazine/dd861344.aspx
In the first code example the one line of code which my question relates to is the following:
VERIFY(SetWindowText(L"Direct2D Sample"));
More specifically that L prefix. I had a litt... | For all new software you should define UNICODE and use wchar_t directly. Using ANSI stirngs will come back to haunt you.
You should just use wchar_t and the wide versions of all the CRT functions (ex: wcscmp instead of strcmp). The TEXT macros and TCHAR etc just exist if your code needs to work in both ANSI and UNICODE... |
1,340,485 | 1,360,952 | Identify user and machine on the local network | In my company we use small application called IPMsg, a messenger kind of tool to pass messages and file to other fellows in company, even it allows to multicast the message.
And also it lists the user name, host name and IP addresses of users.
How can it do that? There is no server present for message routing and when ... | IPMsg is a daemon which listens to incoming connections on a specific port which is the connection port. You can find out which port it used by using Wireshark.
Start wireshark, start listening on the interface where you have connected to LAN and then start sending any message, wireshark will show you the message on th... |
1,340,577 | 1,340,615 | C++ wstring how to assign from NULL-terminated wchar_t array | Most texts on the C++ standard library mention wstring as being the equivalent of string, except parameterized on wchar_t instead of char, and then proceed to demonstrate string only.
Well, sometimes, there are some specific quirks, and here is one: I can't seem to assign a wstring from an NULL-terminated array of 16-b... | Under most Unixes (Mac OS X as well), whar_t represents UTF-32 single code point, and not 16bit utf-16 point like at windows.
So you need to:
Either:
ws.assing(arr,arr + length_of_string);
That would use arr as iterator and copy each short int to wchar_t.
But this would work only if your characters lay in BMP or rep... |
1,340,658 | 1,340,770 | -fno-omit-frame-pointer without optimization | I was wondering what -fno-omit-frame-pointer will do without optimization?
CXXFLAGS = -Wall -ggdb3 -DDEBUG -fno-omit-frame-pointer
Isn't it that fomit-frame-pointer auto turned on at all levels of -O (except -O0)? I assume in my example it is -O0 by default.
Thanks and regards!
| As you already imply yourself, -fno-omit-frame-pointer is just ignored in your case, as the frame pointer wouldn't be ommitted anyways in the default -O0.
|
1,340,729 | 26,853,142 | How do you generate a random double uniformly distributed between 0 and 1 from C++? | How do you generate a random double uniformly distributed between 0 and 1 from C++?
Of course I can think of some answers, but I'd like to know what the standard practice is, to have:
Good standards compliance
Good randomness
Good speed
(speed is more important than randomness for my application).
Thanks a lot!
PS: I... | In C++11 and C++14 we have much better options with the random header. The presentation rand() Considered Harmful by Stephan T. Lavavej explains why we should eschew the use of rand() in C++ in favor of the random header and N3924: Discouraging rand() in C++14 further reinforces this point.
The example below is a mod... |
1,341,399 | 1,341,433 | Rasterizing a 2D polygon | I need to create a binary bitmap from a closed 2D polygon represented as a list of points. Could you please point me to efficient and sufficiently simple algorithms to do that, or, even better, some C++ code?
Thanks a lot!
PS: I would like to avoid adding a dependency to my project. However if you suggest an open-sourc... | The magic google phrase you want is either "non-zero winding rule" or "even odd polygon fill".
See the wikipedia entries for:
non-zero winding rule
even odd polygon fill
Both are very easy to implement and sufficiently fast for most purposes. With some cleverness, they can be made antialiased as well.
|
1,341,528 | 1,343,973 | Find mapping between Windows heap and modules | I am searching for a way to find a mapping between a heap and the module which owns the heap.
I retrieve the heaps in the following way:
HANDLE heaps[1025];
DWORD nheaps = GetProcessHeaps((sizeof(heaps) / sizeof(HANDLE)) - 1, heaps);
for (DWORD i = 0; i < nheaps; ++i) {
// find module which created for heap
// ...... | Add a CreateHeap call to the very beginning of your program and put a breakpoint on it. Run. Step into the call (going to the disassembly level). Set a new breakpoint. Now continue and the breakpoint should be hit each time a new heap is created. The call stack will show you where it came from.
If the heaps are be... |
1,341,793 | 1,341,863 | Symbian character printing | I am attempting to construct a very simple proof of concept that I can write a web service and actually call the service from a symbian environment. The service is a simple Hello service which takes a name in the form of a const char* and returns back a greeting of the form "hello " + name in the form of a char*. My qu... | If the const char* string is in US-ASCII, you can use TDes::Copy to copy it wrapped in a TPtrC8 to a 16-bit descriptor:
const char *who = "world";
TBuf<128> buf;
buf.Copy(TPtrC8((TText8*)who));
console->Printf(_L("hello %S\n"), &buf);
If it is in some other encoding, have a look at the charconv API in the SDK help.
|
1,341,796 | 1,346,204 | Print n levels of callstack? | Using C++ with Visual Studio, I was wondering if there's an API that will print the callstack for me. Preferably, I'd like to print a callstack 5 levels deep. Does windows provide a simple API to allow me to do this?
| There is a number of ways to do this.
See How to Log Stack Frames with Windows x64
In my opinion, the simplest and as well the most reliable way is the Win32 API function:
USHORT WINAPI CaptureStackBackTrace(
__in ULONG FramesToSkip,
__in ULONG FramesToCapture,
__out PVOID *BackTrace,
... |
1,341,903 | 1,342,557 | C++-like usage of Moose with Perl for OOP | I've been playing around with Moose, getting a feel for it. I'd like an example of pure virtual functions like in C++ but in Moose parlance (specifically in a C++-looking way). I know that even with Moose imposing a stricter model than normal Perl, there's still more than one way to do what I'm asking (via method modif... | I can think of this way using roles instead of subclassing:
{
package AbstractRole;
use Moose::Role;
requires 'stuff';
}
{
package Real;
use Moose;
with 'AbstractRole';
}
This will give a compilation error because Real doesn't have stuff defined.
Adding stuff method to Real will now make it ... |
1,342,045 | 1,342,077 | How do I find the largest int in a std::set<int>? | I have a std::set<int>, what's the proper way to find the largest int in this set?
| What comparator are you using?
For the default this will work:
if(!myset.empty())
*myset.rbegin();
else
//the set is empty
This will also be constant time instead of linear like the max_element solution.
|
1,342,118 | 1,342,131 | Is it possible to override the array access operator for pointers to an object in C++? | I'm trying to do some refactoring of code, and have run into a problem. The program has a data manager that returns pointers to arrays of structures as a void*. One of the new types of data, instead of having a single pointer to an array of structures, has two pointers to arrays of numbers. The problem is that all t... | No, it isn't possible - pointers are considered to be of a built-in type and so cannot have their operators overloaded. However, you can certainly
create smart pointer classes (classes that act like pointers, but with added abilities) and overload their operators - take a look at your compiler's implementation of std:... |
1,342,126 | 1,342,207 | Virtual Table layout in memory? | how are virtual tables stored in memory? their layout?
e.g.
class A{
public:
virtual void doSomeWork();
};
class B : public A{
public:
virtual void doSomeWork();
};
How will be the layout of virtual tables of class A and class B in memory?
| As others have said, this is compiler dependant, and not something that you ever really need to think about in day-to-day use of C++. However, if you are simply curious about the issue, you should read Stan Lippman's book Inside the C++ Object Model.
|
1,342,158 | 1,342,195 | How to figure out what value MSVC is using for a preprocessor macro | I'm attempting to use a /D compiler option on MSVC6 to define a string, but there's something weird about using double quotes around it. To debug this problem, it would be extremely helpful for me to be able to see what value the preprocessor is actually substituting into my code where the macro is expanded. Is there... | Try one of the following options to CL.exe:
/E preprocess to stdout
/P preprocess to file
If you're building within Visual Studio, you can specify custom command-line options in one of the project property dialogs.
|
1,342,211 | 1,346,223 | Does SHGetPathFromIDList() (and similar) put a terminating 0 in its argument? | This is actually a question about a huge number of winapi functions.
A typical MS documentation says (from http://msdn.microsoft.com/en-us/library/bb762194(VS.85).aspx ):
BOOL SHGetPathFromIDList(
PCIDLIST_ABSOLUTE pidl,
LPTSTR pszPath
);
pidl [in] The address of an item identifier list that specifies a... | To answer the title question: Yes. It's part of the definition of LPTSTR - a pointer to a string. It is also reflected in the prefix: psz - "Pointer (to) String (terminated by) Zero".
There is a non-null-terminated stringtype as well, but it's rare in userland API's: UNICODE_STRING. You see it mostly in kernel-level A... |
1,342,299 | 1,342,413 | Windows Mobile - Stop Main Phone App | Is there a way to make Windows Mobile not use the main phone app? I have my own phone app that I want to handle phone transactions for a business device.
My app works fine (detects the call and can hang up), but the main phone app still wants to allow the user to answer a call normally. I can try to hide the incomi... | First of all, you should not do it. Replacing system dialer will create you more troubles than you can expect.
If you still want to do it, there is no nice way to do it, even if you opt to use RIL directly. So, there is a trick in which you create a dummy cprog.exe (which does absolutely nothing), and put in the root ... |
1,342,321 | 1,342,352 | Template Partial Specialization - any real-world example? | I am pondering about partial specialization. While I understand the idea, I haven't seen any real-world usage of this technique. Full specialization is used in many places in STL so I don't have a problem with that. Could you educate me about a real-world example where partial specialization is used? If the example is ... | C++0x comes with unique_ptr which is a replacement for auto_ptr which is going to be deprecated.
If you use unique_ptr with an array type, it uses delete[] to free it, and to provide operator[] etc. If you use it with a non-array type, it uses delete. This needs partial template specialization like
template<typename T... |
1,342,480 | 1,342,641 | Check if input is blank when input is declared as double [C++] | I have three variable declared as doubles:
double Delay1 = 0;
double Delay2 = 0;
double Delay3 = 0;
I Then get their values from the user:
cout << "Please Enter Propogation Delay for Satellite #1:";
cin >> Delay1;
...
But when I check these values to see if they are null (user just hit enter and did not put a numbe... | Something like
cin >> Delay1;
if(cin) { ... }
won't work according to your specification, because cin will skip leading whitespace. The user can't just hit enter. He first has to enter some text. If he enters the following
3a
Then the input is read into the double, up to a, where it stops. cin won't find anything wr... |
1,343,046 | 1,343,098 | Speed comparison of 2 loop styles | I'm reading about STL algorithms and the book pointed out that algorithms like find use a while loop rather than a for loop because it is minimal, efficient, and uses one less variable. I decided to do some testing and the results didn't really match up.
The forfind consistently performed better than the whilefind. At ... | if(*p = val) return p;
That should be a ==. So forfind will only go through the entire vector for the first value, 0, and return immediately for numbers 1-9999.
|
1,343,320 | 1,343,365 | When debugging on Windows where does stderr go? | When trying to debug a program on Windows I can't seem to find where the output I push to stderr is going. How do I get a hold of my stderr output? Is there a debugger-level setting (MSVC 9) I can change to redirect stderr to some part of the UI?
Update: I have not looked into TRACE or OutputDebugString, but the code b... | When you have a GUI process stderror should show up in the output window in visual studio. You can open a new console window if you want to have the output go there.look at the output. See my answer to this question. for details.
|
1,343,324 | 1,343,351 | Find out what a random number generator was seeded with in C++ | I've got an unmanaged c++ console application in which I'm using srand() and rand(). I don't need this to solve a particular problem, but was curious: is the original seed passed to srand() stored somewhere in memory that I can query? Is there any way to figure out what the seed was?
| The seed is not required to be stored, only the last random number returned is.
Here's the example from the manpage:
static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int myrand(void) {
next = next * 1103515245 + 12345;
return((unsigned)(next/65536) % 32768);
... |
1,343,577 | 1,343,599 | Checking if a registry key exists | I am looking for a clean way to check if a registry key exists. I had assumed that RegOpenKey would fail if I tried to open a key that didn't exist, but it doesn't.
I could use string processing to find and open the parent key of the one I'm looking for, and then enumerate the subkeys of that key to find out if the one... | First of all don't worry about performance for stuff like this. Unless you are querying it 100x per sec, it will be more than fast enough. Premature optimization will cause you all kinds of headaches.
RegOpenKeyEx will return ERROR_SUCCESS if it finds the key. Just check against this constant and you are good to go.
|
1,343,626 | 1,343,648 | Interprocess Communication in C++ | I have a simple c++ application that generates reports on the back end of my web app (simple LAMP setup). The problem is the back end loads a data file that takes about 1.5GB in memory. This won't scale very well if multiple users are running it simultaneously, so my thought is to split into several programs :
Program... | Use a named mutex/event, basically what this does is allows one thread (process A in your case) to sit there hanging out waiting. Then process B comes along, needing something done, and signals the mutex/event this wakes up process A, and you proceed.
If you are on Microsoft :
Mutex, Event
Ipc on linux works differentl... |
1,343,654 | 1,343,762 | What are the pros & cons of pre-compiled headers specifically in a GNU/Linux environment/tool-chain? | Pre-compiled headers seem like they can save a lot of time in large projects, but also seem to be a pain-in-the-ass that have some gotchas.
What are the pros & cons of using pre-compiled headers, and specifically as it pertains to using them in a Gnu/gcc/Linux environment?
| The only potential benefit to precompiled headers is that if your builds are too slow, precompiled headers might speed them up. Potential cons:
More Makefile dependencies to get right; if they are wrong, you build the wrong thing fast. Not good.
In principle, not every header can be precompiled. (Think about puttin... |
1,343,864 | 1,343,892 | Automatically port conversion elements of C code to C++ | Is there some tool that can automatically convert the following c style code
A *a = b;
to
A *a = (A*)b;
Thanks,
James
| Assuming this is to eliminate compiler errors, I would probably write one myself. Run the compiler on the source, and redirect error messages to a file. Filter out the errors where it complains about the type. For example, in gcc, they will look like this:
a.cc:3: error: invalid conversion from ‘int’ to ‘int*’
This gi... |
1,344,040 | 1,344,086 | documentation for STL | I have spent the last several years fighting tooth and nail to avoid working with C++ so I'm probably one of a very small number of people who likes systems programming and template meta programming but has absolutely no experience when it comes to the STL and very little C++ template experience.
Does anyone know of a... | Here is the reference I'm using. SGI , Offline Download
Here is another reference
|
1,344,052 | 1,350,332 | boost microsec_time_clock.hpp warning C4244 | I'm new in using boost and have a problem. I need shared_mutex function in my project. So I've done
#include "boost/thread/shared_mutex.hpp"
And compiled my project. My MSVC 2005 with "treat warnings as errors" stops compilation because of a warning:
c:\\...\microsec_time_clock.hpp(103) : warning C4244: 'argument' : ... | I'll bet they're doing a += on an unsigned short. The result of the addition gets cast to an int implicitly, then needs to be downcast back to an unsigned short for the assignment.
|
1,344,631 | 1,344,674 | How can I create an executable to run on a certain processor architecture (instead of certain OS)? | So I take my C++ program in Visual studio, compile, and it'll spit out a nice little EXE file. But EXEs will only run on windows, and I hear a lot about how C/C++ compiles into assembly language, which is runs directly on a processor. The EXE runs with the help of windows, or I could have a program that makes an execut... | Let's think about what "run" means...
Something has to load the binary codes into memory. That's an OS feature. The .EXE or binary executable file or bundle or whatever, is formatted in a very OS-specific way so that the OS can load it into memory.
Something has to turn control over to those binary codes. There's th... |
1,344,684 | 1,344,704 | why a variable declared but not used may cause a error? | If i declare a variable but not use it later in the program, the complier will give me a warning, and since "every warning should not be ignored", why the warning is there? and how can it cause a error? thanks!
| First, a minor point: declaring a variable that's never used is a waste of memory, and thus is itself a bug.
Second, and more importantly: you took the trouble of writing out a declaration for a variable you then never used. Since you would not have bothered to declare a variable if you had no plan to use it, this sug... |
1,345,115 | 1,345,139 | C++ class design problem | I have a class that executes the MSNP15 protocol. The protocol requires clients to perform frequent connection/disconnection to various servers like the dispatch server, login server and the switchboard server.
I decided to store the protocol related variables ( like ticket tokens, nonce etc ) as static member variabl... | If you allocate the memory, then you are the one who must release it. Since the members are static, they do not belong to any instance of the class. So you will have to ensure that the memory is released after the last possible use of the character pointers. This is often very difficult to determine.
I think a better i... |
1,345,179 | 1,345,198 | How to Draw Two Detached Rectangles in DirectX using the D3DPT_TRIANGLESTRIP Primitive Type | I am new to DirectX and I am trying to draw two rectangles in one scene using D3DPT_TRIANGLESTRIP. One Rectangle is no problem but two Rectangles is a whole different ball game. Yes i could draw them using four triangles drawn with the D3DPT_TRIANGLELIST primitive type. My curiosity is on the technic involved using D3D... | Add the four vertices for the second rectangle to the vertex buffer, then call DrawPrimitive twice.
g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 );
g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRI... |
1,345,240 | 1,346,014 | Do you know a good freeware that creates C++ or C# classes (data model) from XSD? | I know examples but there are not free tools. Need one that is free and reliable.
Thanks!
| I am not sure what type of "free" you are looking for but I have used the open source codesynthesis xsd tool www.codesynthesis.com/products/xsd/ for c++ data binding.
|
1,345,300 | 1,345,336 | Equivalent code in managed C++ & C# (Events in VB6) | In VB6 events created in an ActiveX component were stated like this:
Public Event ProcessingComplete()
and called in that ActiveX component like:
RaiseEvent ProcessingComplete
I am creating a managed C++ DLL that I want to do the same thing with. It doesnt look like delegates are exactly what I want. I think the more... | It does sound like you want an event. In .NET, an event is just a delegate which by convention has a special signature. Here is a C# example of declaring an event in a class:
public class MyObject
{
// ...
public event EventHandler ProcessingComplete;
// ...
}
EventHandler is a delegate with two parame... |
1,345,305 | 1,373,515 | VTK Delete() and data deletion | I was browsing through the VTK 5.4.2 code, and can't seem to understand how does the Delete() function works. I mean, the Delete() function is in vtkObjectBase and is virtual, but, through what chain of commands is the destructor of the vtkDoubleArray class (for example) executed?
best regards,
mightydodol
| vtkObjectBase Delete() will call UnRegisterInternal. If the classes ReferenceCount is less than or equal to 1 it will call delete on the class.
|
1,345,382 | 1,345,418 | Binding temporary to a lvalue reference | I have the following code
string three()
{
return "three";
}
void mutate(string& ref)
{
}
int main()
{
mutate(three());
return 0;
}
You can see I am passing three() to mutate method. This code compiles well. My understanding is, temporaries can't be assigned to non-const references. If yes, how this pro... | It used to compile in VC6 compiler, so I guess to maintain backward comptibility VS2008 is supporting this non-standard extension. Try with /Za (disable language extension) flag, you should get an error then.
|
1,345,425 | 1,346,810 | How to access Digital I/O using USB | How to access Digital I/O using USB using C or C++ or Vb.net Or C#.net?
| I use the Velleman K8055 USB EXPERIMENT INTERFACE BOARD
It is simple to program for, and has several inputs and outputs
I got one from Maplin for less than £30
|
1,345,478 | 1,345,911 | How to detect the amount of stack space available to my program? | My Win32 C++ application acts as an RPC server - it has a set of functions for processing requests and RPC runtime creates a separate thread and invokes one of my functions in that thread.
In my function I have an std::auto_ptr which is used to control a heap-allocated char[] array of size known at compile time. It acc... | I'm not sure what you're after.
If you just want typical numbers, then go ahead and try! Create a function with nested scopes, each of which allocates some more stack space. Output in each scope. See how far the thing gets.
If you want concrete numbers in a concrete situation, ask yourself what you would want to do o... |
1,345,745 | 1,346,124 | Visual C++ - Why bother with Debug Mode? | So I have just followed the advice in enabling debug symbols for Release mode and after enabling debug symbols, disabling optimization and finding that break-points do work if symbols are complied with a release mode, I find myself wondering...
Isn't the purpose of Debug mode to help you to find bugs?
Why bother with ... | Debug mode doesn't "let bugs slip past you". It inserts checks to catch a large number of bugs, but the presence of these checks may also hide certain other bugs. All the error-checking code catches a lot of errors, but it also acts as padding, and may hide subtle bounds errors.
So that in itself should be plenty of re... |
1,345,885 | 1,345,903 | Best approach for common functionality | I have built up a number of common modules which I have been hitherto keeping in one directory and referencing from the project directories that need them.
I was wondering if there was a better way of doing this ?
Both the common modules and the code using them are written in C++.
| I would suggest creating a static library and linking with it. It's much simpler than a DLL, you don't have to worry about versioning, and all-around you work with them just as you would with your common modules.
EDIT: Basically, a static library is a collection of object files. If you're working with Visual Studio, yo... |
1,345,937 | 1,346,022 | How to get print preview of webpage in smartphone application | how to get an print preview content of an webpage using HTML control or web-browser control in windows mobile smart phone application using c#, c++ or ATL control.
please guide us with any technical detail or any sample application associated with it.
-Thanks in advance.
GrabIt
| if you can use Qt, you can try this
|
1,346,187 | 1,346,379 | WinForms or WPF or Qt for Windows GUI with C/C++ as backend | I am to develop an application on windows. I have never done that before ;-)
I need to do some heavy audio calculation, which has to be written in C/C++. This part will be a room correction algorithm which currently takes about 10 seconds per channel to run in Matlab. It has to be written in C/C++, since it might be po... | I think the biggest drawback to using WPF or WinForms is that you will have to program in two programming languages, which is a big logistics overhead.
I've seen this type of argument before: use C or C++ for low level, something else for high level. In this case Qt/C++ is as high level as WPF/WinForms, with the benefi... |
1,346,207 | 1,346,278 | Qt Application Performance vs. WinAPI/MFC/WTL/ | I'm considering writing a new Windows GUI app, where one of the requirements is that the app must be very responsive, quick to load, and have a light memory footprint.
I've used WTL for previous apps I've built with this type of requirement, but as I use .NET all the time in my day job WTL is getting more and more pain... | Going native API is the most performant choice by definition - anything other than that is a wrapper around native API.
What exactly do you expect to be the performance bottleneck? Any strict numbers? Honestly, vague ,,very responsive, quick to load, and have a light memory footprint'' sounds like a requirement gatheri... |
1,346,287 | 1,346,371 | How to use boost::lambda together with std::find_if? | I have a std::vector and I want to check a specific attribute
of each element. SomeStruct has an attribute 'type'. I want to check this attribute
to be either Type1 or Type2.
My plan is to use boost::lambda.
std::vector<SomeStruct>::const_iterator it =
std::find_if(
vec.begin(), vec.end(),
_1.type =... | std::find_if(
vec.begin(), vec.end(),
bind(&SomeStruct::type, _1) == SomeStruct::Type1 ||
bind(&SomeStruct::type, _1) == SomeStruct::Type2);
|
1,346,355 | 1,346,374 | C++ game and decorator pattern | I'm porting a 2D platformer and I need a good way of getting some extensibility out of my level tiles. I'm not sure if Decorator is correct here, but nothing else comes to mind. Maybe I need something unique.
Anyway, say I have a basic Tile that has things like it's image, and whether the player can pass through it (ba... | How you design your class methods can make a huge difference in how difficult Decorator is to implement - for instance, instead of isLadder() and isLethal() and so on, why not have methods based on the ways in which the player could interact with a tile (enter(from_dir), exit(to_dir)), etc? A lethal tile could override... |
1,346,408 | 1,346,426 | Need help attaching gdb to my project | I use VS2k8 to write and compile (but not run) a program using the MPICH2 libraries on Vista x64. I then use mpiexec from the command line to launch the program (with only 1 process for the purposes of debugging), and I'd like to attach gdb to it. Simply using attach or gdb --pid=### doesn't work (I get the error Can't... | The binary formats of cl.exe (Visual Studio) and gdb are unfortunately incompatible. You won't be able to use gdb for debugging unless you can figure out a way to rebuild the code with gcc. In the meantime, you can debug your program with Visual Studio directly, by going to Tools > Attach to Process (or pressing Ctrl+A... |
1,346,583 | 1,346,631 | Most common reasons for unstable bugs in C++? | I am currently working on a large project, and I spend most of the time debugging. While debugging is a normal process, there are bugs, that are unstable, and these bugs are the greatest pain for the developer. The program does not work, well, sometimes... Sometimes it does, and there is nothing you can do about it.
Wh... | IME the underlying problem in many projects is that developers use low-level features of C++ like manual memory management, C-style string handling, etc. even though they are very rarely ever necessary (and then only well encapsulated in classes). This leads to memory corruption, invalid pointers, buffer overflows, res... |
1,346,989 | 1,347,058 | Catch a type error in C++ | How do i check if a result is of the right type(int, float, double, etc.) and then throw and catch an exception in case it's not?
Thanks all,
Vlad.
| Could you give more detail about what is giving you "a result" you may be able to determine what you need from there and more likely in a better way.
If all you really want is to check the type, use typeid.
More info here
Following Daniel's model of editing posts to actually answer the question after stating something ... |
1,347,248 | 1,347,259 | .Net - Can a Class Library (dll) written in .Net be used by an application written in C or C++? | Let's say I have written a Class Library (dll) in .Net and now I have developers using it in their .Net applications.
However, the library itself could probably be useful also for developers writing natively (in C or C++). So my question is if my managed dll can be used in C or C++?
If not, why? Maybe I must add some ... | The only way to expose a .NET assembly outside of a CLR-based language is through COM Interop. There is nothing that you can do to reference a .NET .dll directly in an unmanaged language.
The reason for this is that the ".dll" file extension used is purely for appearances and the illusion of consistency. .NET generated... |
1,347,592 | 1,348,403 | iptables c++ control | I need to control inbound and outbound traffic to/from a linux box from within a C++ program. I could call iptables from within my program, but I'd much rather cut out the middle man and access the kernel API functions myself.
I believe I need to use libnfnetlink, however, I have not been able to find any API document... | An year back I was having the same requirement and probed around. But after contacting some open source kernel guys this is what I came to know -
The kernel APIs of iptables are not externalised, means to say, they are not documented APIs. In the sense, the APIs can change any moment. They should be used only by the ip... |
1,347,691 | 1,347,786 | Static vs dynamic type checking in C++ | I want to know what are static and dynamic type checking and the differences between them.
| Static type checking means that type checking occurs at compile time. No type information is used at runtime in that case.
Dynamic type checking occurs when type information is used at runtime. C++ uses a mechanism called RTTI (runtime type information) to implement this. The most common example where RTTI is used is t... |
1,348,078 | 1,348,138 | Why STL containers are preferred over MFC containers? | Previously, I used to use MFC collection classes such CArray and CMap. After a while I switched to STL containers and have been using them for a while. Although I find STL much better, I am unable to pin point the exact reasons for it. Some of the reasoning such as :
It requires MFC: does not hold because other parts ... | Ronald Laeremans, VC++ Product Unit Manager, even said to use STL in June 2006:
And frankly the team will give you the same answer. The MFC collection classes are only there for backwards compatibility. C++ has a standard for collection classes and that is the Standards C++ Library. There is no technical drawback for ... |
1,348,636 | 1,349,957 | How to get started with Drivers Programming under windows | I want to start learning drivers programming under windows .
I never programed drivers , and i am looking for information how to get started .
Any tutorials ,links ,book recommendations , and what development tool kit i should start with ? (WDF will be good one ?)
I really want to program following clock link text
Tha... | To interact with USB hardware you would be best served by looking at WinUSB or the Usermode Driver Framework. Usermode drivers are orders of magnitude easier, being able to use a C++/COM(kind of) framework and a normal debugging environment.
Writing kernelmode drivers should be reserved for stuff like video card, disk,... |
1,348,692 | 1,348,731 | Why does C++ define the norm as the Euclidean norm squared? | This may sound like a bit of a rhetorical question, but I ask it here for two reasons:
It took me a while to figure out what C++ std::norm() was doing differently from MATLAB/Octave, so others may stumble upon it here.
I find it odd to define the norm() function as being something different (though closely related) to... | The C++ usage of the word "norm" is rather confusing, since most people have only ever come across norms in the context of vector spaces. If you view the complex numbers as a vector space over the reals, this is definitely not a norm. In fairness to C++, the std::norm( ) function does compute the so-called Field Norm... |
1,348,847 | 1,348,861 | What is it called when you can fill a string with <<< and an end-delimiter? | I know in C++ and in PHP you can fill a string or a file with hard-coded text. If I remember correctly this is how it is supposed to look:
var <<< DELIMITER
Menu for program X
1.Add two numbers
2.Substract two numbers
3.Multiply two numbers
Please pick an option from (0-3);
DELIMITER
This can be used fo... | It's called the HEREDOC syntax in PHP:
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
?>
|
1,349,060 | 1,349,072 | Easiest implement pattern 1 writer - multiple readers with boost library | I develop a module with multiple threads and one Cache in std::map. Some times I need to update cache. In that time all readers must wait, while I do update map.
How can I do this synchronization with boost library?
P.S.: some time ago in Boost was read_write_mutex. But in current releases of Boost it missed.
|
will shared_mutex replace read_write_mutex?
Yes.
...
Basically unique_lock<shared_mutex> will give you a write lock,
shared_lock<shared_mutex> will give you a read lock, and
upgrade_mutex<shared_mutex> will give you a read lock than you can upgrade by
transferring ownership (with move) to a unique_lock<shared_... |
1,349,313 | 1,349,333 | lock free arena allocator implementation - correct? | for a simple pointer-increment allocator (do they have an official name?) I am looking for a lock-free algorithm. It seems trivial, but I'd like to get soem feedback whether my implementaiton is correct.
not threadsafe implementation:
byte * head; // current head of remaining buffer
byte * end; // end of remaining b... | Your current code appears to work. Your code behaves the same as the below code, which is a simple pattern that you can use for implementing any lock-free algorithm that operates on a single word of data without side-effects
do
{
original = *data; // Capture.
result = DoOperation(original); // Attempt operati... |
1,349,375 | 1,349,400 | Qt UI for existing C++ project | I have already written a C++ program and I would like to write a GUI for it. I realize Qt is a wonderful tool, however, Qt has it's own classes, which make me quite confused. eg: instead of String, Qt has a class named QString..
I am wondering if I can mix C++ code and Qt code in C++?
| Yes you can intermix Qt and STL very easily.
The GUI takes QStrings but will silently create these form std::string or char*, QStrings returned from Qt can be converted with toStdString() or toAscii().
Qt includes a set of collection classes but you don't have to use them.
Qt does a good job of looking like modern C++,... |
1,349,447 | 1,349,475 | MSVC's _M_X64 Predefined Macro Clarification | The documentation for MSVC's Predefined Macros state "_M_X64 [is] Defined for x64 processors." What does that mean, exactly? Will it be defined:
When I'm building for x64 processors, or
When I'm building with x64 processors?
Specifically, I'm looking for a compiler switch for the former case, not the latter. Will _M_... | It means that _M_X64 is the target processor. It is what you are building for, not what you are building on.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.