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
|
|---|---|---|---|---|
902,348
| 902,395
|
Point-triangle intersection in 3d from mouse coordinates?
|
I know how to test intersection between a point and a triangle.
...But i dont get it, how i can move the starting position of the point onto the screen plane precisely by using my mouse coordinates, so the point angle should change depending on where mouse cursor is on the screen, also this should work perfectly no matter which perspective angle i am using in my OpenGL application, so the point angle would be different on different perspective angles... gluPerspective() is the function im talking about.
|
Well, gonna take a shot and guess what you mean. The guess is that you would like to pick objects with your mouse. Check out:
glUnProject.
This transforms the screen coordinates back into 3d world coordinates.
Google has more information if you run into problems.
Cheers !
|
902,432
| 902,443
|
When to use Header files that do not declare a class but have function definitions
|
I am fairly new to C++ and I have seen a bunch of code that has method definitions in the header files and they do not declare the header file as a class. Can someone explain to me why and when you would do something like this. Is this a bad practice?
Thanks in advance!
|
Is this a bad practice?
Not in general. There are a lot of libraries that are header only, meaning they only ship header files. This can be seen as a lightweight alternative to compiled libraries.
More importantly, though, there is a case where you cannot use separate precompiled compilation units: templates must be specialized in the same compilation unit in which they get declared. This may sound arcane but it has a simple consequence:
Function (and class) templates cannot be defined inside cpp files and used elsewhere; instead, they have to be defined inside header files directly (with a few notable exceptions).
Additionally, classes in C++ are purely optional – while you can program object oriented in C++, a lot of good code doesn't. Classes supplement algorithms in C++, not the other way round.
|
902,468
| 909,614
|
Is there a way to suppress c++ name mangling?
|
I have a DLL that is written in C++ and I want to suppress the name mangling for a few exported methods. The methods are global and are not members of any class. Is there a way to achieve this?
BTW: I'm using VS2008.
|
"bradtgmurray" is right, but for Visual C++ compilers, you need to explicitly export your function anyway. But using a .DEF file as proposed by "Serge - appTranslator" is the wrong way to do it.
What is the universal way to export symbols on Visual C++ ?
Using the declspec(dllexport/dllimport) instruction, which works for both C and C++ code, decorated or not (whereas, the .DEF is limited to C unless you want to decorate your code by hand).
So, the right way to export undecorated functions in Visual C++ is combining the export "C" idiom, as answered by "bradtgmurray", and the dllimport/dllexport keyword.
An example ?
As an example, I created on Visual C++ an empty DLL project, and wrote two functions, one dubbed CPP because it was decorated, and the other C because it wasn't. The code is:
// Exported header
#ifdef MY_DLL_EXPORTS
#define MY_DLL_API __declspec(dllexport)
#else
#define MY_DLL_API __declspec(dllimport)
#endif
// Decorated function export : ?myCppFunction@@YAHF@Z
MY_DLL_API int myCppFunction(short v) ;
// Undecorated function export : myCFunction
extern "C"
{
MY_DLL_API int myCFunction(short v) ;
} ;
I guess you already know, but for completeness' sake, the MY_DLL_API macro is to be defined in the DLL makefile (i.e. the VCPROJ), but not by DLL users.
The C++ code is easy to write, but for completeness' sake, I'll write it below:
// Decorated function code
MY_DLL_API int myCppFunction(short v)
{
return 42 * v ;
}
extern "C"
{
// Undecorated function code
MY_DLL_API int myCFunction(short v)
{
return 42 * v ;
}
} ;
|
902,599
| 902,815
|
What is the binary format of a floating point number used by C++ on Intel based systems?
|
I am interested to learn about the binary format for a single or a double type used by C++ on Intel based systems.
I have avoided the use of floating point numbers in cases where the data needs to potentially be read or written by another system (i.e. files or networking). I do realise that I could use fixed point numbers instead, and that fixed point is more accurate, but I am interested to learn about the floating point format.
|
Floating-point format is determined by the processor, not the language or compiler. These days almost all processors (including all Intel desktop machines) either have no floating-point unit or have one that complies with IEEE 754. You get two or three different sizes (Intel with SSE offers 32, 64, and 80 bits) and each one has a sign bit, an exponent, and a significand. The number represented is usually given by this formula:
sign * (2**(E-k)) * (1 + S / (2**k'))
where k' is the number of bits in the significand and k is a constant around the middle range of exponents. There are special representations for zero (plus and minus zero) as well as infinities and other "not a number" (NaN) values.
There are definite quirks; for example, the fraction 1/10 cannot be represented exactly as a binary IEEE standard floating-point number. For this reason the IEEE standard also provides for a decimal representation, but this is used primarily by handheld calculators and not by general-purpose computers.
Recommended reading: David Golberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic
|
902,667
| 902,703
|
STL container assignment and const pointers
|
This compiles:
int* p1;
const int* p2;
p2 = p1;
This does not:
vector<int*> v1;
vector<const int*> v2;
v2 = v1; // Error!
v2 = static_cast<vector<const int*> >(v1); // Error!
What are the type equivalence rules for nested const pointers? I thought the conversion would be implicit. Besides, I'd rather not implement point-wise assignment of STL containers, unless I really have to.
|
Direct assignment is not possible. As others explained, the equivalence is not established by the pointer types, but by the container types. In this case, vector doesn't want to accept another vector that has a different, but compatible element type.
No real problem, since you can use the assign member function:
v2.assign(v1.begin(), v1.end());
|
902,687
| 902,702
|
How can a glfwSleep() cause a segfault?
|
in my multithraded application, I'm using a sleep() function (the one from the GLFW library):
glfwSleep(..);
and it apparently leads my application to segfaulting as my call stack shows:
#0 76CFC2BC WaitForSingleObjectEx() (C:\Windows\system32\kernel32.dll:??)
#1 00000016 ??() (??:??)
#2 0000006C ??() (??:??)
#3 00000000 ??() (??:??)
The glfwSleep() is used inside a thread. Is that dangerous? Why is my program segfaulting as a consequence to that?
Edit:
When the parameter of the glfwSleep() is < 0.02 (secs) it doesn't segfault!
Edit 2:
From the official documentation of GLFW :
Writing threaded applications may be
very awkward before you get used to
it, but there are a few key rules that
are fairly simple to follow:
ALWAYS assure exclusive access to data that is shared between threads!
Make sure that threads are synchronized properly!
NEVER busy wait!
I think i got my answer..have to find an alternative now..
Thanks!
|
From the GLFW wiki:
GLFW doesn't work well with GHC
threads, forkIO or threadDelay. So
avoid them if you can.
|
902,747
| 902,764
|
When to use goto instead of control structure nesting?
|
Possible Duplicates:
Valid use of goto for error management in C?
Examples of good gotos in C or C++
GOTO still considered harmful?
To Use GOTO or Not?
The goto statement seems very risky to use. When would it be a good scenario to use a goto statement instead of nesting control statements? Is it even a preferred way of controlling a program flow?
|
GoTo is good just for error handling in VB6, when you program in assembler or for a Pic. In high level programming it's considered a bad practice because "breaks" the program control flow and also makes the code harder to read.
|
902,769
| 902,811
|
How to program hardware performance counters
|
I've been dealing with this problem for my thesis.
The goal is to develop a .net server monitoring tool specifically for windows 2K8 servers.
So far, all I can access are software performance counters. Meaning those that are available through perfmon and the WMI classes.
But then there's also the issue that I need to be able to monitor things like the number of TLB-misses that occur, or the current memory bandwidth. And that's where I'm stuck...
As there is no standard .net way to get these counters I've been reading through some code from open source programs such as Oprofile. But since I don't know what exactly I'm looking for, not much progress has been made on that front.
So I humbly ask if there is somebody here, who has any experience with this kind of thing and could help me out a bit.
Thanks in advance.
|
The most widely used library for reading performance counters is the Performance API (PAPI). PAPI is actually two API's (high-level and low-level). I tend to use the low level one since I find it more intuitive, but that could just be me.
There are two types of events in PAPI. Preset events are supposed to be platform-agnostic, though they can differ subtly depending on how they're counted internally. They do include TLB misses and memory stalls, so maybe you could start there. If that doesn't suit your needs, you may want to have a look at native events, which are specific to your particular hardware and typically include every event that the hardware can count. Use papi_native_aval to get a list of these.
PAPI has support for Windows, but I've actually never tried it. I couldn't find anything in the docs/readmes that referred specifically to Windows 2008, but at the very least perhaps you can look through the source to see how to access the counters you need, even if you can't access them directly.
If you need more, then maybe take a look at perfmon2, which the newer versions of PAPI make use of on Linux, if it's available.
|
902,780
| 902,795
|
Is there a way to read input directly from the keyboard in standard C++?
|
And I know there's std::cin, but that requires the user to enter a string, then press ENTER. Is there a way to simply get the next key that is pushed without needing to press ENTER to confirm
|
You can use
#include <conio.h>
and then catch char with cases such as this
char c;
if (_kbhit())
{
c = getch();
switch(c)
{
case ‘\0H’ :
cout << "up arrow key!" << endl;
break;
}
}
Beware: I have not tried it... and remember to put the whole thing into a "while(true)" to test.
|
903,064
| 903,075
|
Compiler Error: Function call with parameters that may be unsafe
|
Got some code that is not mine and its producing this warning atm:
iehtmlwin.cpp(264) : warning C4996: 'std::basic_string<_Elem,_Traits,_Ax>::copy': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Ax=std::allocator<char>
]
c:\program files (x86)\microsoft visual studio 8\vc\include\xstring(1680) : see declaration of 'std::basic_string<_Elem,_Traits,_Ax>::copy'
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Ax=std::allocator<char>
]
this is the code in question:
HRESULT STDMETHODCALLTYPE Read(void __RPC_FAR *pv, ULONG cb, ULONG __RPC_FAR *pcbRead)
{
if (prepend.size() > 0)
{
int n = min(prepend.size(), cb);
prepend.copy((char *) pv, n);
prepend = prepend.substr(n);
if (pcbRead)
*pcbRead = n;
return S_OK;
};
int rc = Read((char *) pv, cb);
if (pcbRead)
*pcbRead = rc;
return S_OK;
};
and the warning refers to the prepend.copy line. I have tried googling the warning but cant work out what it is on about. Can some one help me solve this please.
Visual Studio 2005 SP1
Windows 7 RC1
.
Edit: prepend is a string which is typedefed
typedef basic_string<char, char_traits<char>, allocator<char> > string;
|
The warning is telling you that you risk a buffer overflow if n is too large -- which you know can't happen because of the way you just computed with a min, but the poor commpiler doesn't. I suggest you take the compiler's own advice and use -D_SCL_SECURE_NO_WARNINGS for this one source file...
|
903,133
| 903,164
|
Tokenize the text depending on some specific rules. Algorithm in C++
|
I am writing a program which will tokenize the input text depending upon some specific rules. I am using C++ for this.
Rules
Letter 'a' should be converted to token 'V-A'
Letter 'p' should be converted to token 'C-PA'
Letter 'pp' should be converted to token 'C-PPA'
Letter 'u' should be converted to token 'V-U'
This is just a sample and in real time I have around 500+ rules like this. If I am providing input as 'appu', it should tokenize like 'V-A + C-PPA + V-U'. I have implemented an algorithm for doing this and wanted to make sure that I am doing the right thing.
Algorithm
All rules will be kept in a XML file with the corresponding mapping to the token. Something like
<rules>
<rule pattern="a" token="V-A" />
<rule pattern="p" token="C-PA" />
<rule pattern="pp" token="C-PPA" />
<rule pattern="u" token="V-U" />
</rules>
1 - When the application starts, read this xml file and keep the values in a 'std::map'. This will be available until the end of the application(singleton pattern implementation).
2 - Iterate the input text characters. For each character, look for a match. If found, become more greedy and look for more matches by taking the next characters from the input text. Do this until we are getting a no match. So for the input text 'appu', first look for a match for 'a'. If found, try to get more match by taking the next character from the input text. So it will try to match 'ap' and found no matches. So it just returns.
3 - Replace the letter 'a' from input text as we got a token for it.
4 - Repeat step 2 and 3 with the remaining characters in the input text.
Here is a more simple explanation of the steps
input-text = 'appu'
tokens-generated=''
// First iteration
character-to-match = 'a'
pattern-found = true
// since pattern found, going recursive and check for more matches
character-to-match = 'ap'
pattern-found = false
tokens-generated = 'V-A'
// since no match found for 'ap', taking the first success and replacing it from input text
input-text = 'ppu'
// second iteration
character-to-match = 'p'
pattern-found = true
// since pattern found, going recursive and check for more matches
character-to-match = 'pp'
pattern-found = true
// since pattern found, going recursive and check for more matches
character-to-match = 'ppu'
pattern-found = false
tokens-generated = 'V-A + C-PPA'
// since no match found for 'ppu', taking the first success and replacing it from input text
input-text = 'u'
// third iteration
character-to-match = 'u'
pattern-found = true
tokens-generated = 'V-A + C-PPA + V-U' // we'r done!
Questions
1 - Is this algorithm looks fine for this problem or is there a better way to address this problem?
2 - If this is the right method, std::map is a good choice here? Or do I need to create my own key/value container?
3 - Is there a library available which can tokenize string like the above?
Any help would be appreciated
:)
|
So you're going through all of the tokens in your map looking for matches? You might as well use a list or array, there; it's going to be an inefficient search regardless.
A much more efficient way of finding just the tokens suitable for starting or continuing a match would be to store them as a trie. A lookup of a letter there would give you a sub-trie which contains only the tokens which have that letter as the first letter, and then you just continue searching downward as far as you can go.
Edit: let me explain this a little further.
First, I should explain that I'm not familiar with these the C++ std::map, beyond the name, which makes this a perfect example of why one learns the theory of this stuff as well as than details of particular libraries in particular programming languages: unless that library is badly misusing the name "map" (which is rather unlikely), the name itself tells me a lot about the characteristics of the data structure. I know, for example, that there's going to be a function that, given a single key and the map, will very efficiently search for and return the value associated with that key, and that there's also likely a function that will give you a list/array/whatever of all of the keys, which you could search yourself using your own code.
My interpretation of your data structure is that you have a map where the keys are what you call a pattern, those being a list (or array, or something of that nature) of characters, and the values are tokens. Thus, you can, given a full pattern, quickly find the token associated with it.
Unfortunately, while such a map is a good match to converting your XML input format to a internal data structure, it's not a good match to the searches you need to do. Note that you're not looking up entire patterns, but the first character of a pattern, producing a set of possible tokens, followed by a lookup of the second character of a pattern from within the set of patterns produced by that first lookup, and so on.
So what you really need is not a single map, but maps of maps of maps, each keyed by a single character. A lookup of "p" on the top level should give you a new map, with two keys: p, producing the C-PPA token, and "anything else", producing the C-PA token. This is effectively a trie data structure.
Does this make sense?
It may help if you start out by writing the parsing code first, in this manner: imagine someone else will write the functions to do the lookups you need, and he's a really good programmer and can do pretty much any magic that you want. Writing the parsing code, concentrate on making that as simple and clean as possible, creating whatever interface using these arbitrary functions you need (while not getting trivial and replacing the whole thing with one function!). Now you can look at the lookup functions you ended up with, and that tells you how you need to access your data structure, which will lead you to the type of data structure you need. Once you've figured that out, you can then work out how to load it up.
|
903,221
| 903,230
|
Press Enter to Continue
|
This doesn't work:
string temp;
cout << "Press Enter to Continue";
cin >> temp;
|
cout << "Press Enter to Continue";
cin.ignore();
or, better:
#include <limits>
cout << "Press Enter to Continue";
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
|
903,228
| 903,234
|
Why use precompiled headers (C/C++)?
|
Why use precompiled headers?
Reading the responses, I suspect what I've been doing with them is kind of stupid:
#pragma once
// Defines used for production versions
#ifndef PRODUCTION
#define eMsg(x) (x) // Show error messages
#define eAsciiMsg(x) (x)
#else
#define eMsg(x) (L"") // Don't show error messages
#define eAsciiMsg(x) ("")
#endif // PRODUCTION
#include "targetver.h"
#include "version.h"
// Enable "unsafe", but much faster string functions
#define _CRT_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
// Standard includes
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <direct.h>
#include <cstring>
#ifdef _DEBUG
#include <cstdlib>
#endif
// Standard Template Library
#include <bitset>
#include <vector>
#include <list>
#include <algorithm>
#include <iterator>
#include <string>
#include <numeric>
// Boost libraries
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/scoped_array.hpp>
//Windows includes
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "FILETIME_Comparisons.h"
#include <shlwapi.h>
#include <Shellapi.h>
#include <psapi.h>
#include <imagehlp.h>
#include <mscat.h>
#include <Softpub.h>
#include <sfc.h>
#pragma comment(lib, "wintrust.lib")
#pragma comment(lib,"kernel32.lib")
#pragma comment(lib,"Psapi.lib")
#pragma comment(lib,"shlwapi.lib")
#pragma comment(lib,"imagehlp.lib")
#pragma comment(lib,"Advapi32.lib")
#pragma comment(lib,"Shell32.lib")
#pragma comment(lib,"Sfc.lib")
#pragma comment(lib,"Version.lib")
// Crypto ++ libraries
#ifdef _DEBUG
#pragma comment(lib,"cryptlibd.lib")
#else
#pragma comment(lib,"cryptlib.lib")
#endif
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <md5.h>
#include <sha.h>
// String libraries
#include "stringUnicodeConversions.h"
#include "expandEnvStrings.h"
#include "randomString.h"
#include "getShortPathName.h"
// Regular Expression Libraries
#include "fpattern.h"
// File Result Record
#include "unixTimeToFileTime.h"
#include "fileData.h"
// Writer
#include "writeFileData.h"
// Criteria Structure System
#include "priorities.h"
#include "criterion.H"
#include "OPSTRUCT.H"
#include "regexClass.H"
#include "FILTER.h"
// Sub Programs Root Class
#include "subProgramClass.h"
// Global data
#include "globalOptions.h"
// Logger
#include "logger.h"
// Console parser
#include "consoleParser.h"
// Timeout handler
#include "timeoutThread.h"
// Zip library
#include "zip.h"
#include "unzip.h"
#include "zipIt.h"
// Scanner
#include "mainScanner.h"
#include "filesScanner.h"
// Sub Programs
#include "volumeEnumerate.h"
#include "clsidCompressor.h"
#include "times.h"
#include "exec.h"
#include "uZip.h"
// 64 bit support
#include "disable64.h"
|
It compiles a lot quicker. C++ compilation takes years without them. Try comparing some time in a large project!
|
903,555
| 903,649
|
C or C++: Libraries for factoring integers?
|
It seems that there are several really fast prime factorization algorithms around (one that looks ideal is quadratic sieving). However, rather than make my own (likely poor) implementation I would like to use a ready-made library for simplicity.
I need to be able to factor integers of up to 15 digits efficiently. Because of that, I'm not looking for the algorithm that necessarily scales asymptotically best since we can assume the numbers being factored are less than 1015.
I've already had a look at some of the implementations listed on Wikipedia's Quadratic Sieve page. However, some of the implementations don't seem well-maintained; some don't have documentation; and so on! I checked if a few well-known libraries, such as Boost, had factorization methods but they don't seem to.
Can anyone recommend a library that fits the above criteria?
|
Check out MSIEVE library for factoring large integers by Jason Papadopoulos.
Msieve is the result of my efforts to understand and optimize how
integers are factored using the most powerful modern algorithms.
This documentation corresponds to version 1.46 of the Msieve library.
Do not expect to become a factoring expert just by reading it. I've
included a relatively complete list of references that you can and
should look up if you want to treat the code as more than a black box
to solve your factoring problems.
|
903,676
| 903,764
|
Initializing a program using a Singleton
|
I have read multiple articles about why singletons are bad.
I know it has few uses like logging but what about initalizing and deinitializing.
Are there any problems doing that?
I have a scripting engine that I need to bind on startup to a library.
Libraries don't have main() so what should I use?
Regular functions or a Singleton.
Can this object be copied somehow:
class
{
public:
static void initialize();
static void deinitialize();
} bootstrap;
If not why do people hide the copy ctor, assignment operator and the ctor?
|
Libraries in C++ have a much simpler way to perform initialization and cleanup. It's the exact same way you'd do it for anything else. RAII.
Wrap everything that needs to be initialized in a class, and perform its initialization in the constructor. Voila, problems solved.
All the usual problems with singletons still apply:
You are going to need more than one instance, even if you hadn't planned for it. If nothing else, you'll want it when unit-testing. Each test should initialize the library from scratch so that it runs in a clean environment. That's hard to do with a singleton approach.
You're screwed as soon as these singletons start referencing each others. Because the actual initialization order isn't visible, you quickly end up with a bunch of circular references resulting in accessing uninitialized singletons or stack overflows or deadlocks or other fun errors which could have been caught at compile-time if you hadn't been obsessed with making everything global.
Multithreading. It's usually a bad idea to force all threads to share the same instance of a class, becaus it forces that class to lock and synchronize everything, which costs a lot of performance, and may lead to deadlocks.
Spaghetti code. You're hiding your code's dependencies every time you use a singleton or a global. It is no longer clear which objects a function depends on, because not all of them are visible as parameters. And because you don't need to add them as parameters, you easily end up adding far more dependencies than necessary. Which is why singletons are almost impossible to remove once you have them.
|
904,346
| 904,365
|
Analyze SSL certificate programmatically or via commandline
|
I'ld like to analyze the certificate of a given url and get some details of it. Do you know any ways to do this? A command-line tool can be something like downloadSSLCert https://my.funny.url/ > certFile and then analyzing it for e.g. the fingerprint of the cert. It can be a command line utility, a C/C++/Objective-C or Java code and will be used on osx >= 10.5
|
You can make an SSL connection from the command line thus:
echo '' | openssl s_client -connect www.google.com:443
The output will contain the X.509 cert in base64 encoding.
To view further details,
... | openssl x509 -fingerprint -text
If you only want the fingerprint, omit the "-text" flag and add "-out /dev/null".
|
904,422
| 904,494
|
How to get a thread to continue after write() has written less bytes than requested?
|
I'm using the following code to write data through a named pipe from one application to another. The thread where the writing is taken place should never be exited. But if r_write() returns less than it should, the thread/program stops for some reason. How can I make the thread continue once write has returned less than it should?
ssize_t r_write(int fd, char *buf, size_t size)
{
char *bufp;
size_t bytestowrite;
ssize_t byteswritten;
size_t totalbytes;
for (bufp = buf, bytestowrite = size, totalbytes = 0;
bytestowrite > 0;
bufp += byteswritten, bytestowrite -= byteswritten) {
byteswritten = write(fd, bufp, bytestowrite);
if ((byteswritten) == -1 && (errno != EINTR))
return -1;
if (byteswritten == -1)
byteswritten = 0;
totalbytes += byteswritten;
}
return totalbytes;
}
void* sendData(void *thread_arg)
{
int fd, ret_val, count, numread;
string word;
char bufpipe[5];
ret_val = mkfifo(pipe, 0777); //make the sprout pipe
if (( ret_val == -1) && (errno != EEXIST))
{
perror("Error creating named pipe");
exit(1);
}
while(1)
{
if(!sproutFeed.empty())
{
string s;
s.clear();
s = sproutFeed.front();
int sizeOfData = s.length();
snprintf(bufpipe, 5, "%04d", sizeOfData);
char stringToSend[strlen(bufpipe) + sizeOfData +1];
bzero(stringToSend, sizeof(stringToSend));
strncpy(stringToSend,bufpipe, strlen(bufpipe));
strncat(stringToSend,s.c_str(),strlen(s.c_str()));
strncat(stringToSend, "\0", strlen("\0"));
int fullSize = strlen(stringToSend);
cout << "sending string" << stringToSend << endl;
fd = open(pipe,O_WRONLY);
int numWrite = r_write(fd, stringToSend, strlen(stringToSend) );
if(numWrite != fullSize)
{
bzero(bufpipe, strlen(bufpipe));
bzero(stringToSend, strlen(stringToSend));
cout << "NOT FULL SIZE WRITE " << endl; //program ends here??
}
else
{
sproutFeed.pop();
bzero(bufpipe, strlen(bufpipe));
bzero(stringToSend, strlen(stringToSend));
}
}
else
{
sleep(1);
}
}
}
|
The write to the FIFO failed. Investigate the value of errno to find out why. Look in errno.h on your system to decipher the value of errno. If the program is ending upon trying to write to the console, the reason may be related.
Also, your loop doesn't appear to be closing the file descriptor for the FIFO (close(fd)).
Finally, you mention multithreading. The standard library stream cout on your system may not (and probably isn't) thread-safe. In that case, writing to the console concurrently from multiple threads will cause unpredictable errors.
|
904,472
| 904,480
|
Templated member function with typedef return value
|
Why does the following code give me an error (g++ 4.1.2)?
template<class A>
class Foo {
public:
typedef std::vector<A> AVec;
AVec* foo();
};
template<class A>
Foo<A>::AVec* Foo<A>::foo() { // error on this line
return NULL;
}
The error is:
error: expected constructor, destructor, or type conversion before '*' token
How am I supposed to define the Foo<A>::foo() function otherwise (with the correct return type)?
|
This is an issue called "two-stage lookup". Basically, since A is a template parameter in foo()'s definition, the compiler can't know when parsing the template for the first time, whether Foo<A>::AVec is a type or even exists (since, for instance, there may exist a specialization of Foo<Bar> which doesn't contain the typedef at all). It will only know what it is during template instantiation, which happens later - and it's too late for this stage.
The correct way would be to use the typename keyword to indicate that this is a type:
template<class A>
class Foo {
public:
typedef std::vector<A> AVec;
AVec* foo();
};
template<class A>
typename Foo<A>::AVec* Foo<A>::foo() {
return NULL;
}
|
904,581
| 904,793
|
Shmem vs tmpfs vs mmap
|
Does someone know how well the following 3 compare in terms of speed:
shared memory
tmpfs (/dev/shm)
mmap (/dev/shm)
Thanks!
|
Read about tmpfs here. The following is copied from that article, explaining the relation between shared memory and tmpfs in particular.
1) There is always a kernel internal mount which you will not see at
all. This is used for shared anonymous mappings and SYSV shared
memory.
This mount does not depend on CONFIG_TMPFS. If CONFIG_TMPFS is not
set the user visible part of tmpfs is not build, but the internal
mechanisms are always present.
2) glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for
POSIX shared memory (shm_open, shm_unlink). Adding the following
line to /etc/fstab should take care of this:
tmpfs /dev/shm tmpfs defaults 0 0
Remember to create the directory that you intend to mount tmpfs on
if necessary (/dev/shm is automagically created if you use devfs).
This mount is _not_ needed for SYSV shared memory. The internal
mount is used for that. (In the 2.3 kernel versions it was
necessary to mount the predecessor of tmpfs (shm fs) to use SYSV
shared memory)
So, when you actually use POSIX shared memory (which i used before, too), then glibc will create a file at /dev/shm, which is used to share data between the applications. The file-descriptor it returns will refer to that file, which you can pass to mmap to tell it to map that file into memory, like it can do with any "real" file either. The techniques you listed are thus complementary. They are not competing. Tmpfs is just the file-system that provides in-memory files as an implementation technique for glibc.
As an example, there is a process running on my box currently having registered such a shared memory object:
# pwd
/dev/shm
# ls -lh
insgesamt 76K
-r-------- 1 js js 65M 24. Mai 16:37 pulse-shm-1802989683
#
|
904,641
| 904,654
|
Linear Search in a Char Array -- C++ (Visual Studio 2005)
|
I am very new to C++ programming and you will see why.
I want to make a character array consisting of a few words that I want to search with a linear search function. Does this array have to be a two-dimensional array? For example:
char Colors[3][6] = {"red", "green", "blue"};
I tried it like this:
char Colors[] = {"red", "green", "blue"};
This gave me a "too many initializers" error.
I assume the 1st method is correct because it states the amount of elements in the array and the maximum length of an element, correct?
Now how would I implement a linear search function to find a word inside that array? Can I do something like the following:
(Assuming the linearSearch function has already been declared)
char searchKey;
char element;
char Colors[3][6] = {"red", "green", "blue"};
printf("Enter the color to look for: \n");
scanf("%s", searchKey);
element = linearSearch(Colors, searchKey, ??); //?? is where I don't know what to enter
if (element != -1)
{
printf("Found the word.\n");
}
else
{
printf("Didn't find the word.\n");
}
Is this possible? If so, what would the declaration look for the linearSearch function? I hope I provided enough information for this to be somewhat usable.
edit: Thanks all for the help, got the program working as intended.
|
You could make your linearSearch function to return the index of the search term in the array. Here is a sample program:
#include <stdio.h>
#include <string.h>
int linearSearch (const char **Array, const char *searchKey, int arraySize) {
for (int i = 0; i < arraySize; ++i) {
if (strcmp(Array[i], searchKey) == 0)
return i;
}
// We didn't find the searchKey in the Array
return -1;
}
int main () {
char *colors[] = { "red", "green", "blue" };
int index = linearSearch (colors, "green", 3);
if (index < 0) { // search string was not found
printf("Search string not found!\n");
}
else {
printf("String %s found at index %d\n", colors[index], index);
}
return 0;
}
We use the strcmp() function to compare the strings. It returns zero if strings match and nonzero if they don't. To use it, you need to include the string.h header.
But, as others have suggested, you should use STL if you can.
|
904,824
| 904,832
|
Can I detect the Java version from native c++
|
I'm writing a complex setup/installer application in native C++/MFC. I would very much like to be able to detect the version of Java that is installed (if any).
Is this possible, and so, how?
|
You could try running java -version in a subprocess (reading that process's output with pipe) and parsing the results (if any); or, you could mess with Windows' registry (which feels even more complicated, but may be less kludgy).
|
905,355
| 905,366
|
How to get the number of characters in a std::string?
|
How should I get the number of characters in a string in C++?
|
If you're using a std::string, call length():
std::string str = "hello";
std::cout << str << ":" << str.length();
// Outputs "hello:5"
If you're using a c-string, call strlen().
const char *str = "hello";
std::cout << str << ":" << strlen(str);
// Outputs "hello:5"
Or, if you happen to like using Pascal-style strings (or f***** strings as Joel Spolsky likes to call them when they have a trailing NULL), just dereference the first character.
const char *str = "\005hello";
std::cout << str + 1 << ":" << *str;
// Outputs "hello:5"
|
905,479
| 905,487
|
std::string length() and size() member functions
|
I was reading the answers for this question and found that there is actually a method called length() for std::string (I always used size()). Is there any specific reason for having this method in std::string class? I read both MSDN and CppRefernce, and they seem to indicate that there is no difference between size() and length(). If that is so, isn't it making more confusing for the user of the class?
|
As per the documentation, these are just synonyms. size() is there to be consistent with other STL containers (like vector, map, etc.) and length() is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length() is there to make things more readable.
|
905,724
| 905,737
|
C++ array[index] vs index[array]
|
Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]
Is the possibility of both array[index] and index[array] a compiler feature or a language feature. How is the second one possible?
|
The compiler will turn
index[array]
into
*(index + array)
With the normal syntax it would turn
array[index]
into
*(array + index)
and thus you see that both expressions evaluate to the same value. This holds for both C and C++.
|
905,765
| 905,779
|
allocating and freeing a char * in c++
|
Hey everyone, I am getting a heap corruption error I cannot figure out.
char * c = (char *) malloc(1);
// main loop
_gcvt_s(c, 100, ball->get_X_Direction(), 10);
if(pushFont(c, (SCREEN_WIDTH - 30), (SCREEN_HEIGHT - 40), message, screen,
font, textColor) == false)
{
//return 1; // error rendering text.
}
// end main loop
free(c);
The above code is the only time I use c pointer, in _gcvt_s and pushFont() which simply accepts a char * as its first parameter, and puts the text on the screen. Other then that I do not use c. When I try to free c after the main loop (which I think I am supposed to do), I get an error saying Visual Studio has acquired an error with the heap (heap corruption).
Commenting out the call to pushFont I still receive the error.
Can anyone explain to me why freeing a character (the 1 byte I allocated on the heap) would give me a heap corruption?
Lastly my main loop does a lot of stuff, a buddy and I are making a pong game with WinSocket, the rest of the main body is the loop for the game. I didnt think it was necessary to post, but I will update my post with the entire main loop if it is necessary, but I believe I am just off with my understanding of malloc() and free().
Thanks all,
|
Doesn't _gcvt_s use the 2nd parameter as the max size of the allocated buffer? You allocate 1 byte but tell _gcvt_s there are 100. So it happily writes up to 100 bytes into the buffer corrupting your heap. Then the free crashes. Allocate 100 bytes if you are going to potentially access 100 bytes.
EDIT: It sounds like you need to learn how C stores and manipulates strings. C stores strings as individual bytes in contiguous runs of memory followed by an extra character to indicate the end of the string. This extra character has an ASCII value of 0 (not the character '0' which is ASCII 48). So if you have a string like "HELLO", it takes 6 bytes to store - one for each of the 5 letters and the terminator.
In order for _gcvt_s() to return the value to your buffer, you need to include enough bytes for the conversion and the extra terminating byte. In the case of _gcvt_s(), you are asking for 10 characters of precision. But you also have to reserve room for the decimal point, the potential negative sign.
According to this [documentation](http://msdn.microsoft.com/en-us/library/a2a85fh5(VS.80).aspx), there is a #define in the headers for the maximum necessary size of the buffer: _CVTBUFSIZE. The example there should help you with this issue.
|
906,196
| 906,891
|
Qt: QList of QButtonGroup
|
Hey! I try to do the following
QList<QButtonGroup*> groups;
for (int i=0; i<nGroup; i++)
{
QButtonGroup *objects = new QButtonGroup(this);
objects->setExclusive(false);
for (int j=0; j<nObject; j++)
{
Led *tempLed = new Led();
tempLed->setAutoExclusive(false);
layout->addWidget(tempLed,j,i,Qt::AlignLeft);
objects->addButton(tempLed);
}
groups.append(objects);
}
And then try to do something like this:
groups.at(1)->button(2)->setChecked(true);
The code compiles, but at runtime throws unhandled exception.
What am I doing wrong?
Any better way to create group of QButtonGroup?
|
The QButtonGroup::button function returns the button for a specific ID, but you didn't use an id when you added the button to the buttongroup. QButtonGroup::button returns 0 in your example leading to a null pointer access exception.
...
objects->addButton(tempLed);
...
If you change the code into
...
objects->addButton(tempLed, j );
...
you original code will work.
I prefer QList::at over QList::operator[] because you don't want to change the value (==pointer) in the list.
|
906,244
| 906,252
|
How can I use a custom type as key for a map in C++?
|
I am trying to assign a custom type as a key for std::map. Here is the type which I am using as key:
struct Foo
{
Foo(std::string s) : foo_value(s){}
bool operator<(const Foo& foo1) { return foo_value < foo1.foo_value; }
bool operator>(const Foo& foo1) { return foo_value > foo1.foo_value; }
std::string foo_value;
};
When used with std::map, I am getting the following error:
error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Foo' (or there is no acceptable conversion) c:\program files\microsoft visual studio 8\vc\include\functional 143
If I change the struct to the one below, everything works:
struct Foo
{
Foo(std::string s) : foo_value(s) {}
friend bool operator<(const Foo& foo,const Foo& foo1) { return foo.foo_value < foo1.foo_value; }
friend bool operator>(const Foo& foo,const Foo& foo1) { return foo.foo_value > foo1.foo_value; }
std::string foo_value;
};
Nothing changed, except that the operator is overloaded as friend. Why does my first code not work?
|
I suspect you need
bool operator<(const Foo& foo1) const;
Note the const after the arguments, this is to make "your" (the left-hand side in the comparison) object constant.
The reason only a single operator is needed is that it is enough to implement the required ordering. To answer the abstract question "does a have to come before b?" it is enough to know whether a is less than b.
|
906,599
| 907,549
|
Why can't I use fopen?
|
In the mold of a previous question I asked about the so-called safe library deprecations, I find myself similarly bemused as to why fopen() should be deprecated.
The function takes two C strings, and returns a FILE* ptr, or NULL on failure. Where are the thread-safety problems / string overrun problems? Or is it something else?
Thanks in advance
|
There is an official ISO/IEC JTC1/SC22/WG14 (C Language) technical report TR24731-1 (bounds checking interfaces) and its rationale available at:
http://www.open-std.org/jtc1/sc22/wg14
There is also work towards TR24731-2 (dynamic allocation functions).
The stated rationale for fopen_s() is:
6.5.2 File access functions
When creating a file, the fopen_s and freopen_s functions improve security by protecting the file from unauthorized access by setting its file protection and opening the file with exclusive access.
The specification says:
6.5.2.1 The fopen_s function
Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
errno_t fopen_s(FILE * restrict * restrict streamptr,
const char * restrict filename,
const char * restrict mode);
Runtime-constraints
None of streamptr, filename, or mode shall be a null pointer.
If there is a runtime-constraint violation, fopen_s does not attempt to open a file.
Furthermore, if streamptr is not a null pointer, fopen_s sets *streamptr to the
null pointer.
Description
The fopen_s function opens the file whose name is the string pointed to by
filename, and associates a stream with it.
The mode string shall be as described for fopen, with the addition that modes starting
with the character ’w’ or ’a’ may be preceded by the character ’u’, see below:
uw truncate to zero length or create text file for writing, default permissions
ua append; open or create text file for writing at end-of-file, default permissions
uwb truncate to zero length or create binary file for writing, default permissions
uab append; open or create binary file for writing at end-of-file, default
permissions
uw+ truncate to zero length or create text file for update, default permissions
ua+ append; open or create text file for update, writing at end-of-file, default
permissions
uw+b or uwb+ truncate to zero length or create binary file for update, default
permissions
ua+b or uab+ append; open or create binary file for update, writing at end-of-file,
default permissions
To the extent that the underlying system supports the concepts, files opened for writing
shall be opened with exclusive (also known as non-shared) access. If the file is being
created, and the first character of the mode string is not ’u’, to the extent that the
underlying system supports it, the file shall have a file permission that prevents other
users on the system from accessing the file. If the file is being created and first character
of the mode string is ’u’, then by the time the file has been closed, it shall have the
system default file access permissions10).
If the file was opened successfully, then the pointer to FILE pointed to by streamptr
will be set to the pointer to the object controlling the opened file. Otherwise, the pointer
to FILE pointed to by streamptr will be set to a null pointer.
Returns
The fopen_s function returns zero if it opened the file. If it did not open the file or if
there was a runtime-constraint violation, fopen_s returns a non-zero value.
10) These are the same permissions that the file would have been created with by fopen.
|
906,667
| 906,845
|
GetDiskFreeSpaceEx with compressed disk
|
I want to get the free space on a compressed disk to show it to a end user. I'm using C++, MFC on Windows 2000 and later. The Windows API offers the GetDiskFreeSpaceEx() function.
However, this function seems to return the "uncompressed" sized of the data. This cause me some problem.
For example :
- Disk size is 100 GB
- Data size is 90 GB
- Compressed data size is 80 GB
The user will see that the disk is 90% full, but in reality, it is only 80% full.
EDIT
As Gleb pointed out, the function is returning the good information.
So here is the new question : is there a way to get both the compressed size and the uncompressed one?
|
I think you would have to map over all files, query with GetFileSize() and GetCompressedFileSize() and sum them up. Use GetFileAttributes() to know if a file is compressed or not, in case only parts of the whole volume is compressed, which might certainly be the case.
Hum, so that's not a trivial
operation. I suppose I must implement
some mechanism to avoid querying all
files size all the time. I mean ... if
I have a 800GB hard drive, it could
take some very long time to get all
file size.
True.
Perhaps start off by a full scan (application startup) and populate your custom data structure, e.g. a hash/map from file name to file data struct/class, then poll the drive with FindFirstChangeNotification() and update your internal structure accordingly.
You might also want to read about "Change Journals". I have never used them myself so don't know how they work, but might be worth checking out.
|
906,734
| 906,794
|
Does C++ do value initialization of a POD typedef?
|
Does C++ do value initialization on simple POD typedefs?
Assuming
typedef T* Ptr;
does
Ptr()
do value-initialization and guarantee to equal (T*)0?
e.g.
Ptr p = Ptr();
return Ptr();
|
It does. For a type T, T() value-initializes an "object" of type T and yields an rvalue expression.
int a = int();
assert(a == 0);
Same for pod-classes:
struct A { int a; };
assert(A().a == 0);
Also true for some non-POD classes that have no user declared constructor:
struct A { ~A() { } int a; };
assert(A().a == 0);
Since you cannot do A a() (creates a function declaration instead), boost has a class value_initialized, allowing to work around that, and C++1x will have the following, alternative, syntax
int a{};
In the dry words of the Standard, this sounds like
The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized
Since a typedef-name is a type-name, which is a simple-type-specifier itself, this works just fine.
|
906,915
| 906,971
|
C++ code performance
|
When is about writing code into C++ using VS2005, how can you measure the performance of your code?
Is any default tool in VS for that? Can I know which function or class slow down my application?
Are other external tools which can be integrated into VS in order to measure the gaps in my code?
|
If you have the Team System edition of Visual Studio 2005, you can use the built-in profiler.
http://msdn.microsoft.com/en-gb/library/z9z62c29(VS.80).aspx
|
907,087
| 907,114
|
Benefit of slist over vector?
|
What I need is just a dynamically growing array. I don't need random access, and I always insert to the end and read it from the beginning to the end.
slist seems to be the first choice, because it provides just enough of what I need. However, I can't tell what benefit I get by using slist instead of vector. Besides, several materials I read about STL say, "vectors are generally the most efficient in time for accessing elements and to add or remove elements from the end of the sequence". Therefore, my question is: for my needs, is slist really a better choice than vector? Thanks in advance.
|
For starters, slist is non-standard.
For your choice, a linked list will be slower than a vector, count on it. There are two reasons contributing to this:
First and foremost, cache locality; vectors store their elements linearly in the RAM which facilitates caching and pre-fetching.
Secondly, appending to a linked list involves dynamic allocations which add a large overhead. By contrast, vectors most of the time do not need to allocate memory.
However, a std::deque will probably be even faster. In-depth performance analysis has shown that, despite bias to the contrary, std::deque is almost always superior to std::vector in performance (if no random access is needed), due to its improved (chunked) memory allocation strategy.
|
907,471
| 907,497
|
C++0x initializer list example
|
I would like to see how this example of existing code would be able to take advantage of the C++0x initializer list feature.
Example0:
#include <vector>
#include <string>
struct Ask {
std::string prompt;
Ask(std::string a_prompt):prompt(a_prompt){}
};
struct AskString : public Ask{
int min;
int max;
AskString(std::string a_prompt, int a_min, int a_max):
Ask(a_prompt), min(a_min), max(a_max){}
};
int main()
{
std::vector<Ask*> ui;
ui.push_back(new AskString("Enter your name: ", 3, 25));
ui.push_back(new AskString("Enter your city: ", 2, 25));
ui.push_back(new Ask("Enter your age: "));
}
Would it support something like this:
Example1:
std::vector<Ask*> ui ={
AskString("Enter your name: ", 3, 25),
AskString("Enter your city: ", 2, 25),
Ask("Enter your age: ")
};
Or must it have literals like this?:
Example2:
std::vector<Ask*> ui ={
{"Enter your name: ", 3, 25},
{"Enter your city: ", 2, 25},
{"Enter your age: "}
};
If so how would the difference between AskString and Ask be handled?
|
You last examples wouldn't be allowed as you ask for pointers but try to provide local temporary objects instead.
std::vector<Ask*> ui ={
new AskString{"Enter your name: ", 3, 25},
new AskString{"Enter your city: ", 2, 25},
new Ask{"Enter your age: "}
};
That would be allowed and there would be no type ambiguity.
That would be right too :
std::vector<Ask*> ui ={
new AskString("Enter your name: ", 3, 25),
new AskString("Enter your city: ", 2, 25),
new Ask("Enter your age: ")
};
And your example is more like :
std::vector<Ask> ui ={ // not pointers
{"Enter your name: "},
{"Enter your city: "},
{"Enter your age: "}
};
std::vector<AskString> uiString ={ // not pointers
{"Enter your name: ", 3, 25},
{"Enter your city: ", 2, 25},
{"Enter your age: ", 7, 42}
};
and again there would be no ambiguity on the types.
|
907,529
| 907,567
|
Is there any API for getting start time of a APACHE WebServer?
|
I am writing a small application to get the various diagnostic parameter of Apache Webserver like time of the start of the server, Worker mode or Prefork mode, server version and many more. I have found few API for getting info about these parameter. But I colud not find nay API for the getting start time of the WebServer. Is there any such kind of API?
If there is no API then there are different approaches like getting the start time using "ps" command in linux/unix and go for similar API in windows.There can be other approach that I could see is to have the time of the APache WebServer in any Variable or file.
Please enlighten me with your valuable comments, approaches.
TIA
Anil
|
Try to have a look at the Apache' the mod_status
|
907,620
| 907,628
|
How to define class-specific << operator in C++
|
Given a class such as:
class Person
{
private:
char *name;
public:
Person()
{
name = new char[20];
}
~Person()
{
delete [] name;
}
}
I want to print to print the name from an instance of this, using a statement like the following:
cout << myPerson << endl;
What do I need to do to define the << output operator for this class?
|
add this in the class:
friend std::ostream& operator<< (std::ostream& out, const Person& P);
and then define the operator<< something like this:
std::ostream& operator<< (std::ostream& out, const Person& P) {
out << P.name;
return out;
}
|
907,812
| 918,344
|
Program crashes when run outside IDE
|
I'm currently working on a C++ program in Windows XP that processes large sets of data. Our largest input file causes the program to terminate unexpectedly with no sort of error message. Interestingly, when the program is run from our IDE (Code::Blocks), the file is processed without any such issues.
As the data is being processed, it's placed into a tree structure. After we finish our computations, the data is moved into a C++ STL vector before being sent off to be rendered in OpenGL.
I was hoping to gain some insight into what might be causing this crash. I've already checked out another post which I can't post a link to since I'm a new user. The issue in the post was quite similar to mine and resulted from an out of bounds index to an array. However, I'm quite sure no such out-of-bounds error is occurring.
I'm wondering if, perhaps, the size of the data set is leading to issues when allocating space for the vector. The systems I've been testing the program on should, in theory, have adequate memory to handle the data (2GB of RAM with the data set taking up approx. 1GB). Of course, if memory serves, the STL vectors simply double their allocated space when their capacity is reached.
Thanks, Eric
|
As it turns out, our hardware is reaching its limit. The program was hitting the system's memory limit and failing miserably. We couldn't even see the error statements being produced until I hooked cerr into a file from the command line (thanks starko). Thanks for all the helpful suggestions!
|
907,901
| 907,915
|
Style question about existing piece of code (C/C++)
|
I just hope the following doesn't seem to you like redundant jabber :)
Anyway, there is that:
for (p = fmt; *p; p++) {
if (*p != '%') {
putchar(*p);
continue;
}
switch (*++p) {
/* Some cases here */
...
}
}
And I wondered why the writer (Kernighan / Ritchie) used the continue in the if statement.
I thought it was for the mere reason that he deemed it would be more elegant than indenting the whole switch under an else statement, what do you think?
|
Probably. The human brain has limited stack space, making it difficult to deal with deeply nested structures. Anything that flattens the information we're expected to parse makes it easier to understand.
Similarly, I normally prefer this:
bool foo(int arg)
{
if(!arg) {
/* arg can't be 0 */
return false;
}
/* Do some work */
return true;
}
To this:
bool foo(int arg)
{
if(!arg) {
/* arg can't be 0 */
return false;
} else {
/* Do some work */
return true;
}
}
Or worse, to this:
bool foo(int arg)
{
if(arg) {
/* Do some work */
return true;
} else {
/* arg can't be 0 */
return false;
}
}
In the last example, the part that does the work might be quite long. By the time the reader gets to the else clause, he may not remember how he got there.
Putting the bail out conditions as close to the beginning helps to assure that people who try to call your functions will have a good idea of what inputs the function expects.
Also, as others pointed out, the continue makes it clear that there's no need to read further into the code inside the loop to determine whether any more processing is done after that point for this case, making the code easier to follow. Again, the fewer things you force the reader to keep track of, the better.
|
908,092
| 908,109
|
In C++, is is possible to throw an exception that will not be caught by std::exception?
|
Question 1:
Is is possible to throw an exception that will not be caught by std::exception?
try
{
}
catch(std::exception & e)
{
}
catch(...)
{
//Is this block needed?
}
Question 2:
Is it better to have:
catch(std::exception & e)
Or
catch(std::exception e)
Or
catch(const std::exception &e)//<--- this is the method I usually use
|
Q1: yes. you can throw any type, not necessary types that inherit from std::exception.
you can write throw 1; to throw and int or throw "hello"; to throw a char*, both of which do not inherit from std::exception. this is however considered bad practice because the user of the class can't expect you to throw anything. If you don't want to inherit from std::exception what you usually do is create your own exception hierarchy.
Q2: catching an exception by value (2nd option) is a bad practice because you force the exception instance to be copied and in that possibly performing allocations which may cause further exceptions.
Using the first option suggest you intend to change e in the catch block which is also something you'd probably like to avoid because exceptions are usually maintained immutable after creation. The only thing that is left is the third option.
|
908,143
| 908,280
|
c++ implementing cancel across thread pools
|
I have several thread pools and I want my application to handle a cancel operation.
To do this I implemented a shared operation controller object which I poll at various spots in each thread pool worker function that is called.
Is this a good model, or is there a better way to do it?
I just worry about having all of these operationController.checkState() littered throughout the code.
|
Yes it's a good approach. Herb Sutter has a nice article comparing it with the alternatives (which are worse).
|
908,227
| 908,683
|
is there any function in C++ that calculates a fingerprint or hash of a string that's guaranteed to be at least 64 bits wide?
|
is there any function in C++ that calculates a fingerprint or hash of a string that's guaranteed to be at least 64 bits wide?
I'd like to replace my unordered_map<string, int> with unordered_map<long long, int>.
Given the answers that I'm getting (thanks Stack Overflow community...) the technique that I'm describing is not well-known. The reason that I want an unordered map of fingerprints instead of strings is for space and speed. The second map does not have to store strings and when doing the lookup, it doesn't incur any extra cache misses to fetch those strings. The only downside is the slight chance of a collision. That's why the key has to be 64 bits: a probability of 2^(-64) is basically an impossibility. Of course, this is predicated on a good hash function, which is exactly what my question is seeking.
Thanks again, Stack Overflowers.
|
c++ has no native 128 Bit type, nor does it have native hashing support. Such extensions for hashing are supposed to be added in TR1, but as far as I am aware 128 bit ints aren't supported my many compilers. (Microsoft supports an __int128 type -- only on x64 platforms though)
I'd expect the functions included with unordered_map would be faster in any case.
If you really do want to do things that way, MD5 provides a good 128 bit hash.
|
908,256
| 908,345
|
Getting template metaprogramming compile-time constants at runtime
|
Background
Consider the following:
template <unsigned N>
struct Fibonacci
{
enum
{
value = Fibonacci<N-1>::value + Fibonacci<N-2>::value
};
};
template <>
struct Fibonacci<1>
{
enum
{
value = 1
};
};
template <>
struct Fibonacci<0>
{
enum
{
value = 0
};
};
This is a common example and we can get the value of a Fibonacci number as a compile-time constant:
int main(void)
{
std::cout << "Fibonacci(15) = ";
std::cout << Fibonacci<15>::value;
std::cout << std::endl;
}
But you obviously cannot get the value at runtime:
int main(void)
{
std::srand(static_cast<unsigned>(std::time(0)));
// ensure the table exists up to a certain size
// (even though the rest of the code won't work)
static const unsigned fibbMax = 20;
Fibonacci<fibbMax>::value;
// get index into sequence
unsigned fibb = std::rand() % fibbMax;
std::cout << "Fibonacci(" << fibb << ") = ";
std::cout << Fibonacci<fibb>::value;
std::cout << std::endl;
}
Because fibb is not a compile-time constant.
Question
So my question is:
What is the best way to peek into this table at run-time? The most obvious solution (and "solution" should be taken lightly), is to have a large switch statement:
unsigned fibonacci(unsigned index)
{
switch (index)
{
case 0:
return Fibonacci<0>::value;
case 1:
return Fibonacci<1>::value;
case 2:
return Fibonacci<2>::value;
.
.
.
case 20:
return Fibonacci<20>::value;
default:
return fibonacci(index - 1) + fibonacci(index - 2);
}
}
int main(void)
{
std::srand(static_cast<unsigned>(std::time(0)));
static const unsigned fibbMax = 20;
// get index into sequence
unsigned fibb = std::rand() % fibbMax;
std::cout << "Fibonacci(" << fibb << ") = ";
std::cout << fibonacci(fibb);
std::cout << std::endl;
}
But now the size of the table is very hard coded and it wouldn't be easy to expand it to say, 40.
The only one I came up with that has a similiar method of query is this:
template <int TableSize = 40>
class FibonacciTable
{
public:
enum
{
max = TableSize
};
static unsigned get(unsigned index)
{
if (index == TableSize)
{
return Fibonacci<TableSize>::value;
}
else
{
// too far, pass downwards
return FibonacciTable<TableSize - 1>::get(index);
}
}
};
template <>
class FibonacciTable<0>
{
public:
enum
{
max = 0
};
static unsigned get(unsigned)
{
// doesn't matter, no where else to go.
// must be 0, or the original value was
// not in table
return 0;
}
};
int main(void)
{
std::srand(static_cast<unsigned>(std::time(0)));
// get index into sequence
unsigned fibb = std::rand() % FibonacciTable<>::max;
std::cout << "Fibonacci(" << fibb << ") = ";
std::cout << FibonacciTable<>::get(fibb);
std::cout << std::endl;
}
Which seems to work great. The only two problems I see are:
Potentially large call stack, since calculating Fibonacci<2> requires we go through TableMax all the way to 2, and:
If the value is outside of the table, it returns zero as opposed to calculating it.
So is there something I am missing? It seems there should be a better way to pick out these values at runtime.
A template metaprogramming version of a switch statement perhaps, that generates a switch statement up to a certain number?
Thanks in advance.
|
template <unsigned long N>
struct Fibonacci
{
enum
{
value = Fibonacci<N-1>::value + Fibonacci<N-2>::value
};
static void add_values(vector<unsigned long>& v)
{
Fibonacci<N-1>::add_values(v);
v.push_back(value);
}
};
template <>
struct Fibonacci<0>
{
enum
{
value = 0
};
static void add_values(vector<unsigned long>& v)
{
v.push_back(value);
}
};
template <>
struct Fibonacci<1>
{
enum
{
value = 1
};
static void add_values(vector<unsigned long>& v)
{
Fibonacci<0>::add_values(v);
v.push_back(value);
}
};
int main()
{
vector<unsigned long> fibonacci_seq;
Fibonacci<45>::add_values(fibonacci_seq);
for (int i = 0; i <= 45; ++i)
cout << "F" << i << " is " << fibonacci_seq[i] << '\n';
}
After much thought into the problem, I came up with this solution. Of course, you still have to add the values to a container at run-time, but (importantly) they are not computed at run-time.
As a side note, it's important not to define Fibonacci<1> above Fibonacci<0>, or your compiler will get very confused when it resolves the call to Fibonacci<0>::add_values, since Fibonacci<0>'s template specialization has not been specified.
Of course, TMP has its limitations: You need a precomputed maximum, and getting the values at run-time requires recursion (since templates are defined recursively).
|
908,272
| 908,295
|
std::back_inserter for a std::set?
|
I guess this is a simple question. I need to do something like this:
std::set<int> s1, s2;
s1 = getAnExcitingSet();
std::transform(s1.begin(), s1.end(), std::back_inserter(s2), ExcitingUnaryFunctor());
Of course, std::back_inserter doesn't work since there's no push_back.
std::inserter also needs an iterator? I haven't used std::inserter so I'm not sure what to do.
Does anyone have an idea?
Of course, my other option is to use a vector for s2, and then just sort it later. Maybe that's better?
|
set doesn't have push_back because the position of an element is determined by the comparator of the set. Use std::inserter and pass it .begin():
std::set<int> s1, s2;
s1 = getAnExcitingSet();
transform(s1.begin(), s1.end(),
std::inserter(s2, s2.begin()), ExcitingUnaryFunctor());
The insert iterator will then call s2.insert(s2.begin(), x) where x is the value passed to the iterator when written to it. The set uses the iterator as a hint where to insert. You could as-well use s2.end().
|
908,392
| 908,396
|
lists find algorithm
|
I'm trying to translate the usage of find function in Matlab to C++. From what I can see from the C++ find function, I can't seem to find in the description anywhere of an easy method of finding the index in the list in which certain conditions is true rather than just comparing for equality between the item that is being searched for and the list of items. Before I implement my own method of performing the find function, it would be great to see if there is any easy, efficient, standard implemented way of doing so already. Thanks in advance.
|
If you're looking for mathing a condition, you want 'find_if'. Using find if will allow you to pass in a predicate which determines whether a given item in the list matches. You will still have to write the matching logic (or find a relevant existing function in the standard algorithms, but its less than having to write the whole framework of 'find'.
|
908,555
| 908,610
|
Is there a function in C++ that creates a .bin file, or is this code missing something?
|
I have a code that looks like this:
int main () {
fstream file;
file.open("test.bin", ios::out | ios::binary);
if(!file.is_open())
{
return -1;
}
int n = 3;
file.write(reinterpret_cast<char*>(&n), sizeof(n));
file.close();
return 0;
}
when I run it alone, it exits with -1, so obviously it failed to open "test.bin". However, if I save a blank notepad file as "test.bin", and run it, it works fine. What I am wondering is how I can get my C++ program to automatically generate an empty file "test.bin" if a file called "test.bin" does not already exist.
|
Your code snippet is wrong since it's trying to write to a file that you've opened for input. If you want to write to the file, simply use ios::out instead of ios::in.
If you want to open the file for reading but create it if it does not exist, you can use:
file.open("test.bin", ios::in | ios::binary);
if(!file.is_open()) {
file.open("test.bin", ios::out | ios::binary);
int n = 3;
file.write(reinterpret_cast<char*>(&n), sizeof(n));
file.close();
file.open("test.bin", ios::in | ios::binary);
if(!file.is_open()) {
return -1;
}
}
This will initialize the file with the integer 3 as the default contents, if it doesn't already exist.
If it does exist, it will leave the contents alone. In either case, you'll have the file open at the first byte.
|
908,605
| 908,615
|
Why doesn't this program read (or write?) correctly from a .bin file? (C++)
|
I created this program:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
fstream file;
file.open("test.bin", ios::in | ios::out | ios::binary);
if(!file.is_open())
{
return -1;
}
int n = 5;
int x;
file.write(reinterpret_cast<char*>(&n), sizeof(n));
file.read(reinterpret_cast<char*>(&x), sizeof(x));
std::cout<<x;
file.close();
std::cin.ignore();
return 0;
}
that's supposed to write an integer "n" into a .bin file "test.bin", then read data from "test.bin" into an integer "x", then displays "x" to the screen.
When I run the program, it displays not 5, but -842150451. Why does this occur, and how can I fix it?
|
Isn't the file.write() moving the current file pointer when you write it, causing you to read data from the first location AFTER the written data?
|
908,847
| 908,873
|
Tokenizing a SIC Assembler source
|
I've pretty much finished coding a SIC assembler for my systems programming class but I'm stumped on the tokenizing part.
For example, take this line of source code:
The format (free format) is: {LABEL} OPCODE {OPERAND{,X}} {COMMENT}
The curls indicate that the field is optional.
Also, each field must be separated by at least one space or tab.
ENDFIL LDA EOF COMMENT GOES HERE
The code above is a bit easier to organize but the following snippet is giving me difficulties.
RSUB COMMENT GOES HERE
My code will read in the first word of the comment as if it were an OPERAND.
Here is my code:
//tokenize line
if(currentLine[0] != ' ' && currentLine[0] != '\t')
{
stringstream stream(currentLine);
stream >> LABEL;
stream >> OPCODE;
stream >> OPERAND;
stream.str("");
if(LABEL.length() > 6 || isdigit(LABEL[0]) || !alphaNum(LABEL))
{
errors[1] = 1;
}
else if(LABEL.length() == currentLine.length())
{
justLabel = true;
errors[6] = 1;
return;
}
}
else
{
stringstream stream(currentLine);
stream >> OPCODE;
stream >> OPERAND;
stream.str("");
}
My professor requires that the assembler be tested with two versions of the source code--one with errors and one without.
The RSUB OPCODE isn't dependent on an OPERAND so I understand that everything after the RSUB OPCODE can be considered a comment, but If the erroneous source code contains a value in the OPERAND field or if an OPCODE which is dependent on an OPERAND is missing the OPERAND value, how do I compensate for this? I need to flag these as errors and print out the erroneous OPERAND value (or lack thereof).
My question is:
How do I prevent the comment portion of the code from being considered an OPERAND?
|
In the assembly languages (as in other programming languages) that I've seen, there's a delimiter that marks a comment: for example a semicolon before the comment:
ENDFIL LDA EOF ;COMMENT GOES HERE
RSUB ;ANOTHER COMMENT GOES HERE
In your syntax however, can you tell whether something is a comment by the amount of whitespace which precedes it on the line, e.g. by the fact that there are two (not just one) whitespace events between the opcode and the comment?
{LABEL}<whitespace>OPCODE<whitespace>{OPERAND{,X}}<whitespace>{COMMENT}
|
908,865
| 908,898
|
Template class expression parameter overloading
|
Hey, I'm trying to figure out if it's possible to "overload" a template class deffinition with expression parameters. Kind of like the following snippet of code.
template<class T>
class Test
{
public:
T testvar;
Test()
{
testvar = 5;
cout << "Testvar: " << testvar << endl;
}
};
template<class T>
class Test<T, int num>
{
public:
T testvar;
Test()
{
testvar = 10;
cout << "Testvar: " << testvar << endl;
cout << "Param: " << num << endl;
}
};
Thanks.
Edit: For the record, i'm trying to do this with C++ if that wasn't obvious... :)
|
Templates allow default template parameters, which can provide something similar to what you're looking for..
template<class T, int num = -1>
class Test
{
public:
T testvar;
Test()
{
testvar = (num == -1 ? 10 : 5);
cout << "Testvar: " << testvar << endl;
if ( num != -1 )
cout << "Param: " << num << endl;
}
};
|
908,946
| 908,961
|
Question about the assignment operator in C++
|
Forgive what might seem to some to be a very simple question, but I have this use case in mind:
struct fraction {
fraction( size_t num, size_t denom ) :
numerator( num ), denominator( denom )
{};
size_t numerator;
size_t denominator;
};
What I would like to do is use statements like:
fraction f(3,5);
...
double v = f;
to have v now hold the value represented by my fraction.
How would I do this in C++?
|
One way to do this is to define a conversion operator:
struct fraction
{
size_t numerator;
size_t denominator;
operator float() const
{
return ((float)numerator)/denominator;
}
};
Most people will prefer not to define an implicit conversion operator as a matter of style. This is because conversion operators tend to act "behind the scenes" and it can be difficult to tell which conversions are being used.
struct fraction
{
size_t numerator;
size_t denominator;
float as_float() const
{
return ((float)numerator)/denominator;
}
};
In this version, you would call the as_float method to get the same result.
|
908,949
| 908,987
|
what happens when you modify an element of an std::set?
|
If I change an element of an std::set, for example, through an iterator, I know it is not "reinserted" or "resorted", but is there any mention of if it triggers undefined behavior? For example, I would imagine insertions would screw up. Is there any mention of specifically what happens?
|
You should not edit the values stored in the set directly. I copied this from MSDN documentation which is somewhat authoritative:
The STL container class set is used
for the storage and retrieval of data
from a collection in which the values
of the elements contained are unique
and serve as the key values according
to which the data is automatically
ordered. The value of an element in a
set may not be changed directly.
Instead, you must delete old values
and insert elements with new values.
Why this is is pretty easy to understand. The set implementation will have no way of knowing you have modified the value behind its back. The normal implementation is a red-black tree. Having changed the value, the position in the tree for that instance will be wrong. You would expect to see all manner of wrong behaviour, such as exists queries returning the wrong result on account of the search going down the wrong branch of the tree.
|
909,314
| 938,861
|
How can I remove a MS Word add-in button?
|
I need to programmatically remove an add-in from MS Word. I have deleted the registry entry corresponding to it, and the button is now disabled (nothing happens when you click it) and the add-in no longer appears on the list of COM Add-ins.
The button, however, remains in the Add-ins ribbon menu. How can I remove that programmatically?
|
No answers after a week. You can tell its a lazy question, can't you?
I am currently using a solution from CodeProject. My code seems to work, but it has not been tested properly yet.
CoInitialize(NULL);
CLSID clsid;
IDispatch *pWApp, *pCommandBars, *pCommandBar, *pCommandBarControls, *pCommandBarControl;
VARIANT v;
HRESULT hr;
hr = CLSIDFromProgID(L"Word.Application", &clsid);
if (SUCCEEDED(hr))
{
hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void **)&pWApp);
if (SUCCEEDED(hr))
{
VariantInit(&v);
hr = OLEMethod(DISPATCH_PROPERTYGET, &v, pWApp, L"Commandbars", 0);
pCommandBars = v.pdispVal;
VariantInit(&v);
hr = OLEMethod(DISPATCH_PROPERTYGET, &v, pCommandBars, L"Count", 0);
INT NumCommBars = v.intVal;
for (INT i = 1; i <= NumCommBars; i++)
{
COleVariant CommandBarIndex((BYTE)i);
VariantInit(&v);
hr = OLEMethod(DISPATCH_PROPERTYGET, &v, pCommandBars, L"Item", 1, CommandBarIndex);
if (FAILED(hr)) continue;
pCommandBar = v.pdispVal;
VariantInit(&v);
hr = OLEMethod(DISPATCH_PROPERTYGET, &v, pCommandBar, L"Controls", 0);
if (FAILED(hr)) continue;
pCommandBarControls = v.pdispVal;
VariantInit(&v);
hr = OLEMethod(DISPATCH_PROPERTYGET, &v, pCommandBarControls, L"Count", 0);
if (FAILED(hr)) continue;
INT NumControls = v.intVal;
for (INT j = 1; j <= NumControls; j++)
{
COleVariant CommandBarControlIndex((BYTE)j);
VariantInit(&v);
hr = OLEMethod(DISPATCH_PROPERTYGET, &v, pCommandBarControls, L"Item", 1, CommandBarControlIndex);
if (FAILED(hr)) continue;
pCommandBarControl = v.pdispVal;
VariantInit(&v);
hr = OLEMethod(DISPATCH_PROPERTYGET, &v, pCommandBarControl, L"Caption", 0);
if (FAILED(hr)) continue;
CString ControlCaption(v.bstrVal);
if (ControlCaption.Find("MyCaption") != -1)
{
OLEMethod(DISPATCH_METHOD, NULL, pCommandBarControl, L"Delete", 0);
}
pCommandBarControl->Release();
}
pCommandBar->Release();
pCommandBarControls->Release();
}
OLEMethod(DISPATCH_METHOD, NULL, pWApp, L"Quit", 0);
pCommandBars->Release();
pWApp->Release();
}
}
CoUninitialize();
Hope this helps others with a similar problem.
|
909,343
| 909,403
|
Reading dynamically allocated arrays into lists
|
Currently, I have been reading lists of data from a binary data file programmatically as follows:
tplR = (double*) malloc(sampleDim[0]*sizeof(double));
printf("tplR = %d\n", fread(tplR, sizeof(double), sampleDim[0], dfile));
However, as I want to use find_if() function on those lists, I would need to get tplR into a list type in stl. In terms of general C++ programming practice, is it usually good practice to make tplR into a list only when I really have to?
If I do make another member variable, for example, tplRList, what would be the easiest way of pushing all sampleDim[0] number of double precision entries into tplRList from tplR? Pushing them one by one until the incremental counter is equal to sampleDim[0]?
Thanks in advance.
|
You can use find_if with the array like this:
bool equals(int p)
{
return p == 9;
}
int main(int argc,char *argv[])
{
int a[10];
for(int i = 0; i < 10; ++i)
{
a[i] = i;
}
int* p = std::find_if(a, a+10, equals);
cout<<*p;
return 0;
}
|
909,437
| 909,527
|
Is there a smart pointer that is automatically nulled when its target is destroyed in C++
|
I've found QPointer. Are there any others?
|
Boost - the weak_ptr has some nice features that make it safe to use, if you are also using shared_ptr. You keep a weak_ptr reference to an instance that is managed by shared_ptr lifetime. When you need to use the underlying instance, convert it to a shared_ptr instance using the constructor of the shared_ptr class, or the lock method. The operation will fail if the underlying instance was deleted. The use is thread safe in the same fashion as the shared_ptr class:
shared_ptr<int> p(new int(5));
weak_ptr<int> q(p);
// some time later
if(shared_ptr<int> r = q.lock())
{
// use *r
}
|
909,775
| 909,806
|
c++ what happens if you print more characters with sprintf, than the char pointer has allocated?
|
I assume this is a common way to use sprintf:
char pText[x];
sprintf(pText, "helloworld %d", Count );
but what exactly happens, if the char pointer has less memory allocated, than it will be print to?
i.e. what if x is smaller than the length of the second parameter of sprintf?
i am asking, since i get some strange behaviour in the code that follows the sprintf statement.
|
It's not possible to answer in general "exactly" what will happen. Doing this invokes what is called Undefined behavior, which basically means that anything might happen.
It's a good idea to simply avoid such cases, and use safe functions where available:
char pText[12];
snprintf(pText, sizeof pText, "helloworld %d", count);
Note how snprintf() takes an additional argument that is the buffer size, and won't write more than there is room for.
|
909,798
| 910,700
|
How to know if a process had been started but crashed in Linux
|
Consider the following situation: -
I am using Linux.
I have doubt that my application has crashed.
I had not enabled core dump.
There is no information in the log.
How can I be sure that, after the system restart my app was started, but now it is not running, because it has crashed.
My app is configured as a service, written in C/C++.
In a way: how can I get all the process/service names that have executed since the system start? Is it even possible?
I know, I can enable logging and start the process again to get the crash.
|
Standard practice is to have a pid file for your daemon (/var/run/$NAME.pid), in which you can find its process id without having to parse the process tree manually. You can then either check the state of that process, or make your daemon respond to a signal (usually SIGHUP), and report its status. It's a good idea to make sure that this pid still belongs to your process too, and the easiest way is to check /proc/$PID/cmdline.
Addendum:
If you're only using newer fedora or ubuntu, your init system is upstart, which has monitoring and triggering capabilities built in.
As @emg-2 noted, BSD process accounting is available, but I don't think it's the correct approach for this situation.
|
910,064
| 911,883
|
how to implemet POSIX select() based behaviour, within boost::asio
|
I've already wasted two days reading documentation of boost::asio
And I still don't know how I could implement blocking select() like function for several sockets using only one thread (using boost framework).
Asynchronous functions of boost::asio return immediately, so there would be a need to put some wait function in main thread until one of the async_read's finishes.
I suspect that this would time consuming, but I'm really restricted by performance requirements.
|
The io_service object is an abstraction of the select function. Set up your sockets and then call the io_service::run member function from your main thread. The io_service::run function will block until all of the work associated with the io_service instance is completed. You can schedule more work in your asynchronous handlers.
You can also use io_service::run_one, io_service::poll, or io_service::poll_one in place of io_service::run.
|
910,215
| 911,939
|
Need for predictable random generator
|
I'm a web-game developer and I got a problem with random numbers. Let's say that a player has 20% chance to get a critical hit with his sword. That means, 1 out of 5 hits should be critical. The problem is I got very bad real life results — sometimes players get 3 crits in 5 hits, sometimes none in 15 hits. Battles are rather short (3-10 hits) so it's important to get good random distribution.
Currently I use PHP mt_rand(), but we are just moving our code to C++, so I want to solve this problem in our game's new engine.
I don't know if the solution is some uniform random generator, or maybe to remember previous random states to force proper distribution.
|
I agree with the earlier answers that real randomness in small runs of some games is undesirable -- it does seem too unfair for some use cases.
I wrote a simple Shuffle Bag like implementation in Ruby and did some testing. The implementation did this:
If it still seems fair or we haven't reached a threshold of minimum rolls, it returns a fair hit based on the normal probability.
If the observed probability from past rolls makes it seem unfair, it returns a "fair-ifying" hit.
It is deemed unfair based on boundary probabilities. For instance, for a probability of 20%, you could set 10% as a lower bound and 40% as an upper bound.
Using those bounds, I found that with runs of 10 hits, 14.2% of the time the true pseudorandom implementation produced results that were out of those bounds. About 11% of the time, 0 critical hits were scored in 10 tries. 3.3% of the time, 5 or more critical hits were landed out of 10. Naturally, using this algorithm (with a minimum roll count of 5), a much smaller amount (0.03%) of the "Fairish" runs were out of bounds. Even if the below implementation is unsuitable (more clever things can be done, certainly), it is worth noting that noticably often your users will feel that it's unfair with a real pseudorandom solution.
Here is the meat of my FairishBag written in Ruby. The whole implementation and quick Monte Carlo simulation is available here (gist).
def fire!
hit = if @rolls >= @min_rolls && observed_probability > @unfair_high
false
elsif @rolls >= @min_rolls && observed_probability < @unfair_low
true
else
rand <= @probability
end
@hits += 1 if hit
@rolls += 1
return hit
end
def observed_probability
@hits.to_f / @rolls
end
Update: Using this method does increase the overall probability of getting a critical hit, to about 22% using the bounds above. You can offset this by setting its "real" probability a little bit lower. A probability of 17.5% with the fairish modification yields an observed long term probability of about 20%, and keeps the short term runs feeling fair.
|
910,230
| 910,452
|
Possible: Program executing Qt3 and Qt4 code?
|
Maybe its a very dumb question but I hope you can give me some answers.
I have a commercial application which uses Qt3 for its GUI and an embedded Python interpreter (command line) for scripting. I want to write a custom plugin for this application which uses Qt4. The plugin is mainly a subclassed QMainWindow-class that is linked into a dll (so I am on Windows) together with a boost python wrapper. The python wrapper should be the interface between my plugin and my commercial application.
So my question: is this possible?? So is running Qt3 code independent from running Qt4 code in the same application.
First experiments resulted in application shutdown, I will try to investigate this further...
Thank you!
Edit:
My application crashed because I didn´t created a QT4 qapplication instance. So when I create the instance everything works well without the additional Qt namespace (which is suggested in the answers, so no need to recompile)! ;)
|
See this thread on a Trolltech forum.
(Well actually that's about Qt3 plugins in a Qt4 app but I suspect the answer is much the same).
Update: link now a dud, but the wayback machine has it.
|
910,320
| 910,331
|
Nice way to do this in modern OO C-like language?
|
I have Tiles which represent the tiles in a game's 2-dimensional world. The tiles can have walls on any number of their 4 sides. I have something like this at the moment:
interface Tile {
boolean isWallAtTop();
boolean isWallAtRight();
boolean isWallAtLeft();
boolean isWallAtBottom();
}
Somewhere else I also have 16 images, one for each possible tile wall configuration. Something like this:
static final Image WALLS_ALL_AROUND = ...
static final Image WALL_ON_TOP_AND_RIGHT = ...
/* etc etc all 16 possibilities */
I want to write a
static Image getWallImage(Tile tile)
What I'd like to avoid is the torture of going through the possibilities like
if (tile.isWallTop && tile.isWallRight
&& !tile.isWallBottom && !tile.isWallLeft) {
return WALL_ON_TOP_AND_RIGHT;
}
Does anyone know a cuter way to do this?
|
Go go gadget bitmasks. Use a 4 bit mask for each tile, stating which side has a wall.
A B C D
Bit A indicates a wall on the top, B the right, C the bottom, D the left. Define constants to help you that you can just logically intersect with the mask, i.e.
if (tile.Walls & (WALL_LEFT | WALL_RIGHT))
// Do stuff
For finding the image, this 4 bit mask produces the 16 possibilities. Use it as an index into an images "array", so you can directly find the correct image without any effort.
|
910,459
| 910,493
|
How to catch file creation and the responsible caller
|
We are using a third part library to render 3d. In this library there is a "memory tracker" functionality that keeps track of all memory the library has allocated and freed during execution. This is a nice feature, since it helps by determining e.g. memory leaks.
By calling a certain function in this library a log file is generated in the current working directory of the process. Lately I've noticed that this file shows up in several different places, so my first thought was of course to always set the current working directory to the folder I want the log to show up in, and this works fine.
However, it turns out that this file is still created in various places without above mentioned function ever being called by the program. Hence, the file must somehow be created by the library without my consent. The creator of this library says that the engine never calls this method internally.
So, in order to prove him wrong (alternatively proving myself to be stupid (won't be the first time though)), I need a way to catch exactly when this file is created. FindFirstChangeNotification() will not do, since this will only provide me with information that something happened in some folder. Ideally I'd like to (either in process or out of process) intercept when this happens and somehow inject a process exception (e.g. make WinDbg catch this), so I through the callstack get the information I want.
Any suggestions are welcome.
Cheers!
|
You could try:
Use a tool like FileMon or Process Explorer, they might be enough to track it down.
Use a hooking a library and replace CreateFile (or more functions if you need to) with your own function. I've had good experience with Detours, it has some really nice examples that you could use straight out of the box.
|
910,619
| 910,661
|
Generating a Hardware-ID on Windows
|
What is the best way to generate a unique hardware ID on Microsoft Windows with C++ that is not easily spoofable (with for example changing the MAC Address)?
|
Windows stores a unique Guid per machine in the registry at:
HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\MachineGuid
|
910,854
| 952,125
|
What is a good platform for devoloping web services in C++?
|
We're looking at developing a Web Service to function as a basis for a browser display/gui for a networked security prototype written in C++. My experience with web services has been limited to Java. I prefer Web Services in Java because it's on the "beaten path".
One sure was to do this would be to simply code a Java client which invokes the web service, and call it as a command line with parameters from the C++ code.
It's not ideal, since generally speaking an API is preferable, but in this case it would work and be a pretty safe solution.
A resource which does handles web service development in C++ is called gSOAP, at this url: http://gsoap2.sourceforge.net
Any thought on which is a better approach? Has anyone used gSOAP, and if so, what did you think?
|
My colleague ended up using a combination of Axis2 / java (for the service) and gsoap for the client. He created the wsdl from the Java service by generating it from a C++ header (using c2wsdl (?) or something like that. He said it was better than using a Java interface because that generated two sets of wsdl, for seperate versions of soap.
Then he used wsdl2java to generate the webservice and a test web client. Once we got that working, he used gsoap to create the web client (in C++), and it worked fine.
thanks for all the answers! I ended using a combination of them.
|
911,035
| 911,076
|
"Uint32", "int16" and the like; are they standard c++?
|
I'm quite new to c++, but I've got the hang of the fundamentals. I've come across the use of "Uint32" (in various capitalizations) and similar data types when reading other's code, but I can't find any documentation mentioning them. I understand that "Uint32" is an unsigned int with 32 bits, but my compiler doesn't. I'm using visual c++ express, and it doesn't recognize any form of it from what I can tell.
Is there some compilers that reads those data types by default, or have these programmers declared them themselves as classes or #define constants?
I can see a point in using them to know exactly how long your integer will be, since the normal declaration seems to vary depending on the system. Is there any other pros or cons using them?
|
Visual c++ doesn't support the fixed-width integer types, because it doesn't include support for C99. Check out the answers to my question on this subject for various options you have for using them.
|
911,263
| 911,304
|
What is a good implementation of a peer-to-peer chat program with a server for assigning connections in C++?
|
For a while, I've been interested in creating a proof-of-concept chat program using C++. I have given the idea a lot of thought and even wrote down the beginnings of how I would design the system, but I have hit a barrier in my thinking when it comes to the implementation.
I want to know what an implementation of a peer-to-peer chat client with a server to route connections would look like in C++.
The server would be used as a central registry of the peers, but not used as the primary connection. The server would not interact with the clients in any way except to assign connections between peers to achieve an optimal path between peers. In a first version, it would merely be a directory to which all clients connect, and the clients can then use the directory to connect to the other clients available for chat. (I hope that explains it a bit more). :)
|
You should look at the XMPP stuff. It is all about routing and co-ordinating messaging. It uses de-centralization and a peer-to-peer like architecture.
There are also plenty of open source implementations. For example,
Jabber.org
|
911,565
| 913,177
|
select(), recv() and EWOULDBLOCK on non-blocking sockets
|
I would like to know if the following scenario is real?!
select() (RD) on non-blocking TCP socket says that the socket is ready
following recv() would return EWOULDBLOCK despite the call to select()
|
I am aware of an error in a popular desktop operating where O_NONBLOCK TCP sockets, particularly those running over the loopback interface, can sometimes return EAGAIN from recv() after select() reports the socket is ready for reading. In my case, this happens after the other side half-closes the sending stream.
For more details, see the source code for t_nx.ml in the NX library of my OCaml Network Application Environment distribution. (link)
|
911,740
| 911,758
|
Warning about hiding member variables?
|
The following code snippet has a memory leak that I spent too much time chasing down. The problem is that inside Foo(), the local variable x_ hides the member variable x_. It's quite annoying too, because the compiler could have warned me about it. Is there a flag in GCC for such a warning? (For the curious: I have arrived at the buggy code by first using a local variable, then changing it to a member variable, but forgetting to remove the type declaration.)
struct A {
A() x_(NULL) {}
~A() {
delete x_;
}
void Foo() {
HugeThingy* x_ = new HugeThingy();
x_->Bar("I. Need. Garbage. Collection. Now.");
}
HugeThingy* x_;
DISALLOW_COPY_AND_ASSIGN(A); // Macro to prevent copy/assign.
}
|
Use -Wshadow.
By the way, neither -W nor -Wall enables -Wshadow.
It's nice to have the compiler help avoid this kind of problem, but that won't even be necessary if you use conventions that help avoid creating it in the first place, such reserving names of the form x_ for member variables, not local variables.
|
912,256
| 912,315
|
What is faster (x < 0) or (x == -1)?
|
Variable x is int with possible values: -1, 0, 1, 2, 3.
Which expression will be faster (in CPU ticks):
1. (x < 0)
2. (x == -1)
Language: C/C++, but I suppose all other languages will have the same.
P.S. I personally think that answer is (x < 0).
More widely for gurus: what if x from -1 to 2^30?
|
That depends entirely on the ISA you're compiling for, and the quality of your compiler's optimizer. Don't optimize prematurely: profile first to find your bottlenecks.
That said, in x86, you'll find that both are equally fast in most cases. In both cases, you'll have a comparison (cmp) and a conditional jump (jCC) instructions. However, for (x < 0), there may be some instances where the compiler can elide the cmp instruction, speeding up your code by one whole cycle.
Specifically, if the value x is stored in a register and was recently the result of an arithmetic operation (such as add, or sub, but there are many more possibilities) that sets the sign flag SF in the EFLAGS register, then there's no need for the cmp instruction, and the compiler can emit just a js instruction. There's no simple jCC instruction that jumps when the input was -1.
|
912,269
| 912,628
|
Remote proxy with shared memory in C++
|
Suppose I have a daemon that is sharing it's internal state to various applications via shared memory. Processes can send IPC messages to the daemon on a named pipe to perform various operations. In this scenario, I would like to create a C++ wrapper class for clients that acts as a kind of "Remote Proxy" to hide some of the gory details (synchronization, message passing, etc) from clients and make it easier to isolate code for unit tests.
I have three questions:
Generally, is this a good idea/approach?
Do you have any tips or gotchas for synchronization in this setup, or is it enough to use a standard reader-writer mutex setup?
Are there any frameworks that I should consider?
The target in question is an embedded linux system with a 2.18 kernel, therefore there are limitations on memory and compiler features.
|
Herb Sutter had an article Sharing Is the Root of All Contention that I broadly agree with; if you are using a shared memory architecture, you are exposing yourself to quite a bit of potential threading problems.
A client/server model can make things drastically simpler, where clients write to the named server pipe, and the server writes back on a unique client pipe (or use sockets). It would also make unit testing simpler (since you don't have to worry about testing shared memory), could avoid mutexing, etc.
|
912,279
| 912,294
|
Append digit to an int without converting to string?
|
Is there a safe way of adding a digit at the end of an integer without converting it to a string and without using stringstreams ?
I tried to google the answer for this and most solutions suggested converting it to a string and using stringstreams but I would like to keep it as an integer to ensure data integrity and to avoid converting types.
I also read a solution which suggested to multiply the int by 10 and then adding the digit, however this might cause an integer overflow.
Is this safe to do or is there a better method for doing this? And if I do this multiply by 10 and add the digits solution, what precautions should I take?
|
Your best bet is the multiplication by 10 and addition of the value. You could do a naive check like so:
assert(digit >= 0 && digit < 10);
newValue = (oldValue * 10) + digit;
if (newValue < oldValue)
{
// overflow
}
|
912,469
| 912,666
|
Is the following code using std::set "legal"?
|
I have this code:
set<int>::iterator new_end =
set_difference(set1.begin(), set1.end(),
set2.begin(), set2.end(),
set1.begin());
set1.erase(new_end, set1.end);
It compiles and runs fine in visual studio. However, in a previous question, people stated that a set's iterators are supposed to be const. I don't see anything like that in the standard. Can someone tell me where it says that, or if this is well-defined behavior?
If it's not, please provide code that does what I need. Is there a way to do this without creating a temporary set?
|
Your code violates a couple of the invariants for set_difference. From page 420 of the Josuttis Book:
The caller must ensure that the destination range is big enough or that insert iterators are used.
The destination range should not overlap the source ranges.
You're trying to write back over the first set, which is not allowed. You need to write someplace other than the source ranges - for that we can use a third set:
std::set<int> set3;
std::set_difference(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::inserter(set3, set3.begin()));
The second argument to std::inserter is a hint for where the elements should be inserted. It's only a hint, however, rest assured that the elements will end up in the right place. set3 is initially empty, so begin() is about the only hint we can give.
After the call to set_difference, set3 will contain what you tried to make set1 contain in your original code. You can go on using set3 or swap it with set1 if you prefer.
Update:
I'm not sure about the performance of this, but if you just want to remove all elements from set1 that appear in set2, you can try:
for (std::set<int>::iterator i = set2.begin(); i != set2.end(); ++i)
{
set1.erase(*i);
}
|
912,660
| 912,729
|
Is it any good to define trivial inlined methods twice based to debug / release -state of the project?
|
I've always wondered, if it's good or bad practice to define trivial method twice, depending
if the project's on debug / release -state. This is for inlining them. For instance, Foo.h:
class Foo
{
public:
...
const bool& IsBoolean() const;
private:
bool _boolean;
};
#ifndef _DEBUG
/** We're in release, so let's advice compiler to inline this...
*
*
*/
inline const bool& Foo::IsBoolean() const
{
return _boolean;
}
#endif
And now, in Foo.cpp:
#include "Foo.h"
...
#ifdef _DEBUG
/** We're debugging this, no need for inlining...
*
*
*/
const bool& Foo::IsBoolean() const
{
return _boolean;
}
#endif
Is this completely useless? For example due to compiler's (MSVC) ability to inline / optimize methods all by itself?
Nevertheless, this is something I've been using for years now. Please correct me, if I'm completely wrong here...
|
It's a waste of time, for several reasons.
The inline keyword is a hint that the compiler may ignore at will. Just like it is free to inline even if the keyword is not specified. So whether or not you add it probably won't change anything for the compiler
Further, any functions defined inside the class definition are implicitly inlined. That is why short functions like getters and setters are almost always defined inside the class definition.
Next, if you want to mark a function as inline, there's no reason not to do it in debug builds as well.
The inline keyword has almost nothing to do with the compiler actually inlining functions. They are separate concepts. A function marked inline by the programmer means that the linker shouldn't worry if it sees multiple identical definitions. That typically happens if the function is defined in a header, which gets included into multiple compilation units. If the function is marked inline, the linker will merge the definitions together. If it isn't, you get an error. In other words, adding and removing this keyword will cause compiler errors. That's probably not what you want.
The only reason there is a bit of overlap between the C++ inline keyword and the compiler optimization is that if a function is marked inline, it is safe to #include it in every compilation unit, which means the definition will always be visible when the function is called. And that makes it easire for the compiler to inline calls to the function.
Finally, inlining is not always a performance improvement. It is easy to create a situation where inlining does nothing more than make the code size explode, cause more cache misses, and overall, slow down your code. That is one of the reasons why inline is (at best) treated as a hint by the optimizer. At worst, it is ignored entirely.
So what you're doing will 1) cause compiler errors in debug mode that didn't exist in release builds, and 2) have no effect on performance.
|
912,850
| 912,980
|
C++ Intellectual Property Protection/Anti-Reversing
|
I've seen a lot of discussion on here about copy protection. I am more interested in anti-reversing and IP protection.
There are solutions such as Safenet and HASP that claim to encrypt the binary, but are these protected from reversing when used with a valid key?
What kinds of strategies can be used to obfuscate code and throw off reversers? Are there any decent commercial implementations out there?
I know most protection schemes can be cracked, but the goal here is to delay the ability to reverse the software in question, and make it much more blatant if another company tries to implement these methods.
|
There are solutions such as Safenet and HASP that claim to encrypt the binary, but are these protected from reversing when used with a valid key?
No. A dedicated reverse engineer can decrypt it, because the operating system has to be able to decrypt it in order to run it.
Personally, I wouldn't worry. Admittedly I don't know anything about your business, but it seems to me that reverse engineering C++ is relatively difficult compared to languages like Java or .NET. That will be enough protection to see off all but the most determined attackers.
However, a determined attacker will always be able to get past whatever you implement, because at some point it has to be turned into a bunch of CPU instructions and executed. You can't prevent them from reading that.
But that's a lot of effort for a non-trivial program. It seems a lot more likely to me that somebody might just create a competitor after seeing your program in action (or even just from your marketing material). It's probably easier than trying to reverse engineer yours, and avoids any potential legal issues. That isn't something you can (or should) prevent.
|
912,946
| 912,981
|
Preproccessor ignore
|
I am migrating from Visual Studio 6 to Visual Studio 2008 and I have a function of a component I am using named SetDefaultPrinter.
Unfortunately there is a windows library function now, SetDefaultPrinter, with the same name. And the macro associated with it is getting in the way of me using my function.
This is my workaround I have to call my function:
#undef SetDefaultPrinter
pNova->SetDefaultPrinter();
#ifdef UNICODE
#define SetDefaultPrinter SetDefaultPrinterW
#else
#define SetDefaultPrinter SetDefaultPrinterA
#endif // !UNICODE
Is there a less ugly way around this? And no, I do not have control over that external component to change the name of the function.
|
This is why C++ added namespaces; too bad the Windows definitions can't use them.
In another source module, where you do NOT include windows.h or any other Windows include files, generate a stub function to call your clashing function.
void MySetDefaultPrinter(CNova * pNova)
{
pNova->SetDefaultPrinter();
}
|
912,993
| 913,066
|
Same class with 2 or 1 template parameter
|
How do I make a template specialization that takes 2 parameters versus the normal 1?
I was building a pointer class and now I thought about extending to make an array but if I try something like this:
template<class T,int s> class pointer{};
template<class T> class pointer{};
class mama{};
int main(){
pointer<mama> m;
}
It gives me an error. Template... redeclared with 1 parameter.
I need it specialized because pointer<mama,10> has size() and operator[] while pointer<mama> doesn't, it has operator-> and *.
|
You could make a general template for the array case:
template <class TElem, int size = 0>
class pointer
{
// stuff to represent an array pointer
};
Then a partial specialization:
template <class TElem>
class pointer<TElem, 0>
{
// completely different stuff for a non-array pointer
};
By defining a specialized version for the case where size=0, you can actually give that a totally different implementation, but with the same name.
However, it might be clearer just to give it a different name.
|
913,060
| 913,348
|
DLL Dependencies - different on different systems?
|
I created an application, with the mingw compiler in a WinXP system. It worked fine. I then tried to run it in an older WinXP box(this has been in the shelf for some 6 months). The application terminated with an exception --'The application could not initialize (0xc0150002)'.
Running depends.exe on the app shows two unavailable dlls(ieshims.dll and wer.dll) in the target. But, in the build system, the dependency tree is different and has lesser dlls than in the old winxp box. I have all the latest windows updates done on both the systems.
Why is it that the same application depends on different dlls on different systems?
How do i solve this problem?
Thanks,
sundar
|
When I've had this problem, it was due to not installing certain redistributables on the target machine (you may need to look for a VS 2008 redistributable, or even .Net framework redistributable).
|
913,070
| 913,399
|
Why does push_back or push_front invalidate a deque's iterators?
|
As the title asks.
My understanding of a deque was that it allocated "blocks". I don't see how allocating more space invalidates iterators, and if anything, one would think that a deque's iterators would have more guarantees than a vector's, not less.
|
The C++ standard doesn't specify how deque is implemented. It isn't required to allocate new space by allocating a new chunk and chaining it on to the previous ones, all that's required is that insertion at each end be amortized constant time.
So, while it's easy to see how to implement deque such that it gives the guarantee you want[*], that's not the only way to do it.
[*] Iterators have a reference to an element, plus a reference to the block it's in so that they can continue forward/back off the ends of the block when they reach them. Plus I suppose a reference to the deque itself, so that operator+ can be constant-time as expected for random-access iterators -- following a chain of links from block to block isn't good enough.
|
913,338
| 913,381
|
How to statically assert a common property of many classes
|
Let's say I have 3 classes. I expect sizeof() each class to be exactly the same--say 512 bytes.
How can I use something like BOOST_STATIC_ASSERT to apply to all of them such that
I only need to use BOOST_STATIC_ASSERT in a single place (DRY principle)
Evaluated once at compile-time and not run-time
Note: we can use whatever C++ techniques we want (create more class , use inheritance, etc)
My naive solution is presented below:
class A { ...stuff }; BOOST_STATIC_ASSERT( sizeof(A) == 512 );
class B { ...stuff }; BOOST_STATIC_ASSERT( sizeof(B) == 512 );
class C { ...stuff }; BOOST_STATIC_ASSERT( sizeof(C) == 512 );
|
This seems to work with gcc 4.0.1 and boost 1.39:
template <typename T, size_t S>
struct enforce_size
{
enforce_size()
{
BOOST_STATIC_ASSERT( sizeof( T ) == S );
}
};
class A: enforce_size<A,512> { /* stuff */ };
|
913,344
| 913,356
|
How can I remove the VS warning C4091: 'typedef ' : ignored on left of 'SPREADSHEET' when no variable is declared
|
This warning is triggered multiple times in my code by the same declaration, which reads :
// Spreadsheet structure
typedef struct SPREADSHEET
{
int ID; // ID of the spreadsheet
UINT nLines; // Number of lines
void CopyFrom(const SPREADSHEET* src)
{
ID = src->ID;
nLines = src->nLines;
}
};
I don't want to just turn off that warning,
but rather change the code so that the warning doesn't come up !
NOTE : I don't want to declare any variables here (it's a header file), only define what the struct 'SPREADSHEET' should include...
|
Delete typedef. It's the C way of declaring structs, C++ does it automatically for you.
|
913,386
| 913,393
|
How Do I Deal with Static Objects when Overloading new and delete to Find Memory Leaks?
|
I'm trying to detect memory leaks by globally overloading new and delete for debug builds and maintaining a list of allocated blocks. This works, but incorrectly reports leaks for some static objects. For example a static std::vector itself is not allocated using new and delete but its internal buffers are. Since my detection code runs before the main function returns the destructors of these objects are not yet called so they haven't deleted their buffers yet and this appears as a "leak".
One workaround I've found is by deleting and placement newing each static object to clear out their buffers before I check for leaks:
std::vector<int> f;
f.~std::vector<int>();
new (&f) std::vector<int>();
This is really ugly though and including cleanup code that isn't required seems bad. Is there some way of getting my code to run after the statics have been destroyed? (even if it's Microsoft-specific)
|
You need to look into std::allocator - the second template parameter of almost all STL containers.
|
913,397
| 913,421
|
find_if function build problems
|
I'm trying to build the following block of code in a 1-file .cpp file:
#include <iostream>
#include <algorithm>
using namespace std;
class test
{
public:
int a[10];
int index;
test();
~test();
bool equals(int p);
void search();
};
test::test()
{
int temp[10] = {4, 9, 5, 6, 9, 10, 9, 255, 60, 0};
memcpy(a, temp, sizeof(temp));
index = -1;
}
bool test::equals(int p)
{
return p == 9;
}
void test::search()
{
int* p = std::find_if(a, a+10, &test::equals);
while (p != a+10)
{
cout<< *p;
index = p - a;
p = std::find_if(p+1, a+10, &test::equals);
}
}
int main(int argc, char *argv[])
{
test object;
object.search();
return 0;
}
I am getting an error as shown below, and I'm not sure exactly what's happening when I use the find_if function in a member method of a class, and I'm getting this error whenever I am doing so.
1>c:\program files\microsoft visual studio 8\vc\include\algorithm(87) : error C2064: term does not evaluate to a function taking 1 arguments
1> c:\program files\microsoft visual studio 8\vc\include\algorithm(96) : see reference to function template instantiation '_InIt std::_Find_if(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _InIt=int *,
1> _Pr=bool (__thiscall test::* )(int)
1> ]
1> c:\testprogram\nomfc\main.cpp(32) : see reference to function template instantiation '_InIt std::find_if(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _InIt=int *,
1> _Pr=bool (__thiscall test::* )(int)
1> ]
|
The find_if function expects an object which is callable as a function with no parameters. This is something like a free function, a function object or a static class function. You passed in the address of the equals member function which is none of these. You could resolve this by making the equals function a free function or a static function, since it does not require any members of the test instance.
// static
class test
{
public:
static bool equals(int p); // etc
};
int* p = std::find_if(a, a+10, &test::equals);
// free
bool equals(int p)
{
return p == 9;
}
int* p = std::find_if(a, a+10, equals);
If your real code example requires that it be a member function, then you need to pass in a function object that acts as a closure over the class instance. I favour using the Boost bind method for this, but there are other methods as well.
int* p = std::find_if(a, a+10, boost::bind(&test::equals, this, _1));
|
913,405
| 913,423
|
How to store the integer value "0" in a .bin file? (C++)
|
EDIT: Apparently, the problem is in the read function: I checked the data in a hex editer
02 00 00 00 01 00 00 00 00 00 00 00
So the zero is being stored as zero, just not read as zero.
Because when I use my normal store-in-bin file function:
int a = 0;
file.write(reinterpret_cast<char*>(&a), sizeof(a));
It stores 0 as the char version, or "\0", which obviously isn't stored (because it's a null value?) so when I call my function to read the zero value, it reads the value right after it (or right before if it would be the last in the file). So how can I store zero in a .bin file properly?
EDIT: Here are some of the functions relating to the read/write process:
//Init program: creates a sector.bin for another program to read from.
#include<fstream>
using namespace std;
int main()
{
fstream file;
file.open("sector.bin", ios::out | ios::binary);
if(!file.is_open())
{
file.open("sector.bin", ios::out | ios::binary);
file.close();
file.open("sector.bin", ios::out | ios::binary);
if(!file.is_open())
{
return -1;
}
}
file.seekp(file.beg);
int a = 2;
int b = 1;
int c = 0;
file.write(reinterpret_cast<char*>(&a), sizeof(a));
file.write(reinterpret_cast<char*>(&b), sizeof(b));
file.write(reinterpret_cast<char*>(&c), sizeof(c));
file.close();
return 0;
}
//Read function: part of another program that intializes variables based off
//of sector.bin
void sector::Init(std::fstream& file)
{
int top_i = FileRead(file,0);
std::cout<<top_i<<std::endl;
for(int i = 0; i < top_i; i++)
{
accessLV[i] = FileRead(file,i+1);
std::cout<<accessLV[i]<<std::endl;
}
std::cin.ignore();
viral_data.add(new X1(5,5,'X'));
viral_data.add(new X1(9,9,'X'));
player.set(0,0,'O');
return;
}
//the FileRead used in init
int FileRead(std::fstream& file, int pos)
{
int data;
file.seekg(file.beg + pos);
file.read(reinterpret_cast<char*>(&data), sizeof(data));
return data;
}
Also, the output for using sector::Init is as follows:
2
1
1
The ouput that I was trying to write into the bin was
2
1
0
So either the 0 is being read/written as a 1, or its not being written and Init is reading the last value twice.
|
It's not clear what do you mean by "storing integer value 0" in a file. Files contain bytes, not integers. Do you need to store sizeof(int) 0-bytes, or just one '\0' byte?
P.S. I also would guess the problem might be in your read code. Did you look at your .bin file in a hex editor?
P.P.S. Your problem is in seekg() function usage. Instead of passing the offset in bytes, you pass pos. It should be pos * sizeof(int) instead.
|
913,505
| 913,572
|
Casting void pointers, depending on data (C++)
|
Basically what I want to do is, depending on the some variable, to cast a void pointer into a different datatype. For example (the 'cast' variable is just something in order to get my point across):
void* ptr = some data;
int temp = some data;
int i = 0;
...
if(temp == 32) cast = (uint32*)
else if(temp == 16) cast = (uint16*)
else cast = (uint8*)
i = someArray[*((cast)ptr)];
Is there anything in C++ that can do something like this (since you can't actually assign a variable to be just (uint32*) or something similar)? I apologize if this isn't clear, any help would be greatly appreciated.
|
The "correct" way:
union MyUnion
{
uint32 asUint32;
uint16 asUint16;
uint8 asUint8;
}
uint32 to_index(int size, MyUnion* ptr)
{
if (size== 32) return ptr->asUint32;
if (size== 16) return ptr->asUint16;
if (size== 8) return ptr->asUint8;
}
i = someArray[to_index(temp,ptr)]
[update: fixed dumb typo]
|
913,573
| 913,582
|
learn and practice c++
|
I'm trying to learn c++ and I really want to do a lot of coding but I'm not sure what I can code.. Tbh, book exercises are not very interesting to me (usually because they're just too short). I like to code OS related stuff like I/O stuff..
I'm thinking of looking at linux and try mimicking some of the tools there.. is that a good idea?
|
Rewriting tools is a good idea - my C++ professor made us rewrite all the standard library string functions by hand before we were allowed to use them in our homework assignments so that is something that may help you as well. You could also check out Project Euler.
|
913,738
| 913,831
|
Where does _CrtDbgReportW ouput in Windows Mobile?
|
I am using ASSERTE macro to check for pre-conditions. According to its definition it is using ASSERT_BASE, which in turn calls _CrtDbgReportW to print out the message. Where does _CrtDbgReportW output goes to?
I would assume that if the application is started from debugger, it would go to debugger window. Where would the messages go if it is not under debugger?
|
The output for _CrtDbgReportW depends on how you set it up. By default it sends it to the OutputDebugString API.
Debuggers trap the OutputDebugString output and normally display them in the debugger window as you suggest.
There are also applications that trap the output like DebugView that you can use for PC applications.
Update: I missed the Windows Mobile bit. I still beleave that it's output to the OutputDebugString but I don't know of any third party application that works. The only way I know of to trap the OutputDebugString output under Windows Mobile is to use the Debugging Functions DebugActiveProcess / WaitForDebugEvent to trap the OUTPUT_DEBUG_STRING_EVENT events and write them out somewhere.
|
914,032
| 914,045
|
How can I transform a string into an abbreviated form?
|
I want to fit strings into a specific width. Example, "Hello world" -> "...world", "Hello...", "He...rld". Do you know where I can find code for that? It's a neat trick, very useful for representing information, and I'd like to add it in my applications (of course).
Edit: Sorry, I forgot to mention the Font part. Not just for fixed width strings but according to the font face.
|
It's a pretty simple algorithm to write yourself if you can't find it anywhere - the pseudocode would be something like:
if theString.Length > desiredWidth:
theString = theString.Left(desiredWidth-3) + "...";
or if you want the ellipsis at the start of the string, that second line would be:
theString = "..." + theString.Right(desiredWidth-3);
or if you want it in the middle:
theString = theString.Left((desiredWidth-3)/2) + "..." + theString.Right((desiredWidth-3)/2 + ((desiredWidth-3) mod 2))
Edit:
I'll assume you're using MFC. Since you're wanting it with fonts, you could use the CDC::GetOutputTextExtent function. Try:
CString fullString
CSize size = pDC->GetOutputTextExtent(fullString);
bool isTooWide = size.cx > desiredWidth;
If that's too big, then you can then do a search to try and find the longest string you can fit; and it could be as clever a search as you want - for instance, you could just try "Hello Worl..." and then "Hello Wor..." and then "Hello Wo..."; removing one character until you find it fits. Alternatively, you could do a binary search - try "Hello Worl..." - if that doesn't work, then just use half the characters of the original text: "Hello..." - if that fits, try halfway between it and : "Hello Wo..." until you find the longest that does still fit. Or you could try some estimating heuristic (divide the total length by the desired length, proportionately estimate the required number of characters, and search from there.
The simple solution is something like:
unsigned int numberOfCharsToUse = fullString.GetLength();
bool isTooWide = true;
CString ellipsis = "...";
while (isTooWide)
{
numberOfCharsToUse--;
CString string = fullString.Left(numberOfCharsToUse) + ellipsis;
CSize size = pDC->GetOutputTextExtent(string);
isTooWide = size.cx > desiredWidth;
}
|
914,184
| 914,296
|
Further std::set woes
|
I asked this question earlier. I am intrigued by std::set but I have another confusing scenario.
Namely, is the following code legal, portable c++ for T=std::vector and T=std::set:
template <typename T>
void remove_elements(T& collection, int removal_value)
{
typename T::iterator new_end =
std::remove(collection.begin(), collection.end(), removal_value);
collection.erase(new_end, collection.end());
}
According to the SGI reference, set::iterator and set::const_iterator are the same, so I don't know if this is legit. However, I can't seem to find another way to get the operation I need to work regardless of type. I could resort to template specialization, however it would be nice not to have to specialize in the first place.
|
erase-remove idiom works only for sequence containers. For the standard associative containers it will not work and the solution is not so straightforward.
Two approaches :
Use remove_copy_if to copy all the
values into another temporary
container and then swap the contents
of the original container with those
of temporary one. [Refer my answer to related Q]
The other one would be loop to walk
the container elements and post increment the iterator when you pass it to erase.
Refer this Q for more details: remove_if equivalent for std::map
Also, refer Item 9. Choose carefully among erasing options from Effective STL by Scott Meyers.
|
914,351
| 914,410
|
Is it possible for a library consumer to override C++ exceptions handling?
|
I have a C++ DLL with code like this:
LogMessage( "Hello world" );
try {
throw new int;
} catch( int* e ) {
LogMessage( "Caught exception" );
delete e;
}
LogMessage( "Done" );
This DLL is loaded by some third-party application and the code above is invoked. The problem is only the first LogMessage is invoked - even though there's an exception handler the control flow is transferred to the unknown.
I see this and can't decide whether it's some obscure bug to be investigated or just the evil force of the consumer application.
Is it really possible for a consumer application to override the C++ exception handling in a DLL?
EDIT: The problem resolved after thinking on all things to check outlined in the answers. In real code it's not just throw, there'a a special function for throwing exceptions that has a call to MessageBoxW() Win32 call in debug version. And the consumer application had troubles showing the message box (it's an NT service) and effectively hung up. So it's not a problem of C++ exceptions handling in any way.
|
The code looks OK to me, but I'd be tempted to put a few more catch clauses in to see if it's hitting one of the other ones. Namely, I'd put in:
catch (const std::exception &ex) {
... log exception ...
}
catch (...) {
... log exception ..
}
I would expect that it'll either hit the pointer catch (even if that's really not a good idea, see the link that Igor Oks provided) or the std::exception in case it can't allocated the memory. That said, it should hit one of the three catch clauses so there is no way for the exception to escape the DLL.
I'd also change the object thrown to a value type (even if it is int) and update the catch clause accordingly to see if you get changed behaviour that way.
|
914,399
| 6,641,319
|
Boost Fusion articles, examples, tutorials?
|
Do you know any good resources/articles/examples of boost::fusion library usage?
Boost Fusion looks extremely interesting, I think I understand how it works and how to use the basics, but I'm looking for some resources that show any interesting usage/practices e.g. articles or blogs (apart from boost.org itself).
|
I thought the comment by johannes-schaub-litb should be an answer, as I nearly overlooked it.
So here it is:
Johannes' excellent example.
There are also some other examples in Stackoverflow. I particularly liked the first answer here.
|
914,442
| 914,485
|
Mahjong-solitaire solver algorithm, which needs a speed-up
|
I'm developing a Mahjong-solitaire solver and so far, I'm doing pretty good. However,
it is not so fast as I would like it to be so I'm asking for any additional optimization
techniques you guys might know of.
All the tiles are known from the layouts, but the solution isn't. At the moment, I have few
rules which guarantee safe removal of certain pairs of same tiles (which cannot be an obstacle to possible solution).
For clarity, a tile is free when it can be picked any time and tile is loose, when it doesn't bound any other tiles at all.
If there's four free free tiles available, remove them immediately.
If there's three tiles that can be picked up and at least one of them is a loose tile, remove the non-loose ones.
If there's three tiles that can be picked up and only one free tile (two looses), remove the free and one random loose.
If there's three loose tiles available, remove two of them (doesn't matter which ones).
Since there is four times the exact same tile, if two of them are left, remove them since they're the only ones left.
My algorithm searches solution in multiple threads recursively. Once a branch is finished (to a position where there is no more moves) and it didn't lead to a solution, it puts the position in a vector containing bad ones. Now, every time a new branch is launched it'll iterate via the bad positions to check, if that particular position has been already checked.
This process continues until solution is found or all possible positions are being checked.
This works nicely on a layout which contains, say, 36 or 72 tiles. But when there's more,
this algorithm becomes pretty much useless due to huge amount of positions to search from.
So, I ask you once more, if any of you have good ideas how to implement more rules for safe tile-removal or any other particular speed-up regarding the algorithm.
Very best regards,
nhaa123
|
I don't completely understand how your solver works. When you have a choice of moves, how do you decide which possibility to explore first?
If you pick an arbitrary one, it's not good enough - it's just brute search, basically. You might need to explore the "better branches" first. To determine which branches are "better", you need a heuristic function that evaluates a position. Then, you can use one of popular heuristic search algorithms. Check these:
A* search
beam search
(Google is your friend)
|
914,460
| 914,480
|
Vector of pointers template clearing function fails to compile with "undefined reference" message
|
For a program of mine I made a small function to clear the various std::vectors of pointers that I have.
template <class S>
void clearPtrVector(std::vector<S*> &a,int size)
{
for(size_t i = 0; i < size; i++)
delete a[i];
a.clear();
}
I must have done something wrong here though since when calling this function in a destructor like so :
clearPtrVector(neurons,neurons.size());
I get the following undefined reference two times:
undefined reference to `void clearPtrVector<Neuron>(std::vector<Neuron*,std::allocator<Neuron*> >&, int)'
I have to admit I am not familiar with what the std::allocator is, so I can not guess what the problem might be here. Any help is really appreciated. Thanks in advance!
-Lefteris
|
Hot Fix
Write following instead:
template <class Vector>
void clearPtrVector(Vector &a)
{
for(size_t i = 0; i < a.size(); i++)
delete a[i];
a.clear();
}
Make sure you define the template somewhere where compiler can see it before each use of the template. If you do not create a declaration, you should be safe, as otherwise you should get a compile error. If you do create a declaration for any reason, be double carefull to include definition everywhere as needed.
Redesign
That said, I think the proper solution would be to rethink your design and to use a container which will handle the destruction properly, so that you do not have to do it manually, which is tedious, and almost impossible to do correctly if you need exception safety. Use std::shared_ptr instead of raw pointers, or std::auto_ptr with a container which is able to hold them (std::vector cannot store auto_ptr values). One possible solution would be to use Boost Pointer Container
|
914,567
| 919,868
|
How to remove the GtkTreeView sorting arrow?
|
I need to remove the sorting arrow from a column header. This can be done by calling set_sort_indicator(false) on the column.
The arrow isn't displayed, but the space for it seems to still be reserved. If the title of the column is big enough to fill all the header, the last part is clipped (where the arrow should be).
Is there a way to make the title fill the whole header?
|
This seems to be a bit weird in GTK+. I downloaded and read through relevant parts of the GtkTreeViewColumn's code, and it seems to use this logic:
if (tree_column->show_sort_indicator ||
(GTK_IS_TREE_SORTABLE (model) && tree_column->sort_column_id >= 0))
gtk_widget_show (arrow);
else
gtk_widget_hide (arrow);
Where arrow is the widget holding the arrow. This seems to indicate that the arrow widget is always packed into the horizontal box that makes up the column's header, and then just hidden (not removed) if it's not supposed to be visible. That will mean it's still there in the box, occupying space and causing the label to be clipped.
I'd recommend searching through the GTK+ bugtracker for an issue about this, and if none is found, create one.
|
914,595
| 4,037,644
|
Is there a way to configure the details of MSVS static code analysis?
|
Static code analysis tool in MSVS (for C++) has plenty of false positives, and some of them are in Windows SDK files. Is there a way to configure it in order to improve quality and ignore stable SDK files?
|
Finally I found what I was looking for - here is the answer directly from MSDN's http://msdn.microsoft.com/en-us/library/zyhb0b82.aspx (VS2010 specific):
#include <codeanalysis\warnings.h>
#pragma warning( push )
#pragma warning ( disable : ALL_CODE_ANALYSIS_WARNINGS )
#include <third-party include files here>
#pragma warning( pop )
|
914,596
| 914,621
|
Information on L-Systems
|
I am about to start a project for university to build a procedural city for a pre existing project.
I was wondering if any of you have had any experience coding L-Systems before and know a good place for me to start out. I have done a bit of work before using procedural methods and Perlin Noise and fBm so I get the premise of what an L-System is in the fractal sense. I am more looking for a place where maybe can push me in the direction of coding the L-System.
Any help or technical documents you can point me towards would be great.
|
I did a project on using L-Systems to procedurally generate 3D trees and found the book "The Algorithmic Beauty of Plants" helpful. It's available for free at that link. Not directly related to procedural cities, but very interesting, and a good resource to learn about L-Systems, I think.
|
914,613
| 914,625
|
What exactly is the effect of Ctrl-C on C++ Win32 console applications?
|
Is it possible to handle this event in some way?
What happens in terms of stack unwinding and deallocation of static/global objects?
|
EDIT: SIGINT, not SIGTERM. And Assaf reports that no objects are destroyed (at least on Windows) for unhanded SIGINT.
The system sends a SIGINT. This concept applies (with some variance) for all C implementations. To handle it, you call signal, specifying a signal handler. See the documentation on the signal function at Open Group and MSDN.
The second question is a little trickier, and may depend on implementation. The best bet is to handle the signal, which allows you to use delete and exit() manually.
|
914,723
| 915,126
|
How to port USB RNDIS device driver?
|
Firstly: I am totally a newbie for this kind of work.
I have a USB rndis device driver for some hardware only working in XP/2000/Vista. But I want to port this to CE or Linux, and vendor also says that developer should do that.
In summary, I have XP drivers and Interface/End point configurations the driver has. And I have two questions related:
Why do I need to write a driver to communicate the device using IP number? Does not Windows support that by default?
If so what do I need to know to port the driver to another OS? I used windriver, it got the configurations, but what can I do next? What else should I know about the device?
|
I can't answer to you question directly, but there is the Synce project, that is
MS ActiveSync replacement for linux. It allows to communicate with Windows Mobile devices via rndis. So if you walk over site you will find the the source of usb-rndis-lite driver for linux.
May be this can be used as some starting point for your work.
|
914,861
| 914,950
|
Disallowing creation of the temporary objects
|
While debugging crash in a multithreaded application I finally located the problem in this statement:
CSingleLock(&m_criticalSection, TRUE);
Notice that it is creating an unnamed object of CSingleLock class and hence the critical section object gets unlocked immediately after this statement. This is obviously not what the coder wanted. This error was caused by a simple typing mistake. My question is, is there someway I can prevent the temporary object of a class being created at the compile time itself i.e. the above type of code should generate a compiler error. In general, I think whenever a class tries to do some sort of resource acquisition then the temporary object of that class should not be allowed. Is there any way to enforce it?
|
Edit: As j_random_hacker notes, it is possible to force the user to declare a named object in order to take out a lock.
However, even if creation of temporaries was somehow banned for your class, then the user could make a similar mistake:
// take out a lock:
if (m_multiThreaded)
{
CSingleLock c(&m_criticalSection, TRUE);
}
// do other stuff, assuming lock is held
Ultimately, the user has to understand the impact of a line of code that they write. In this case, they have to know that they're creating an object and they have to know how long it lasts.
Another likely mistake:
CSingleLock *c = new CSingleLock(&m_criticalSection, TRUE);
// do other stuff, don't call delete on c...
Which would lead you to ask "Is there any way I can stop the user of my class from allocating it on the heap"? To which the answer would be the same.
In C++0x there will be another way to do all this, by using lambdas. Define a function:
template <class TLock, class TLockedOperation>
void WithLock(TLock *lock, const TLockedOperation &op)
{
CSingleLock c(lock, TRUE);
op();
}
That function captures the correct usage of CSingleLock. Now let users do this:
WithLock(&m_criticalSection,
[&] {
// do stuff, lock is held in this context.
});
This is much harder for the user to screw up. The syntax looks weird at first, but [&] followed by a code block means "Define a function that takes no args, and if I refer to anything by name and it is the name of something outside (e.g. a local variable in the containing function) let me access it by non-const reference, so I can modify it.)
|
914,952
| 914,969
|
Is there a way to subscribe to IIs application pool events?
|
I'm in the need of monitoring IIs (v6) events.
More specifically the application pool and Web Site events. Is there some API or WMI instrumentation to do this? This is not from an application perpective, but from an adminsitration perspective.
I am not interested in starting, stopping or recycling programmatically. I'm interested in monitoring the status.
Polling is not very elegant, are there any events that I can hook into?
From managed or unmanaged code, it doesn't matter.
|
These links might help you:
http://leandrodg.wordpress.com/2008/02/12/find-and-recycle-current-application-pool-programmatically-for-iis-6/
http://forums.iis.net/t/1148327.aspx
|
915,106
| 915,116
|
C++: syntax for accessing member struct from pointer to class
|
I'm trying to access a member structs variables, but I can't seem to get the syntax right.
The two compile errors pr. access are:
error C2274: 'function-style cast' : illegal as right side of '.' operator
error C2228: left of '.otherdata' must have class/struct/union
I have tried various changes, but none successful.
#include <iostream>
using std::cout;
class Foo{
public:
struct Bar{
int otherdata;
};
int somedata;
};
int main(){
Foo foo;
foo.Bar.otherdata = 5;
cout << foo.Bar.otherdata;
return 0;
}
|
You only define a struct there, not allocate one. Try this:
class Foo{
public:
struct Bar{
int otherdata;
} mybar;
int somedata;
};
int main(){
Foo foo;
foo.mybar.otherdata = 5;
cout << foo.mybar.otherdata;
return 0;
}
If you want to reuse the struct in other classes, you can also define the struct outside:
struct Bar {
int otherdata;
};
class Foo {
public:
Bar mybar;
int somedata;
}
|
915,172
| 915,199
|
C++ Templates: Coding error or compiler bug?
|
I'm trying to use templates to get std:list of items, where each item has a pointer to the list which contains it, but I keep hitting a compiler message.
Here's a very stripped down version of the code.
template <class E> class Item
{
public:
E* owner; // pointer to list that owns us.
};
template <class E> class BaseList: public std::list<E>
{
protected:
typedef std::list<E> inherited;
public:
void push_back(const E &e)
{
E tmp(e);
tmp.owner = this; // This line gives the error.
inherited::push_back(tmp);
}
};
class MyList;
class MyItem : public Item<MyList>
{
};
class MyList : public BaseList<MyItem>
{
};
void foo() // test code to instantiate template
{
MyList l;
MyItem m;
l.push_back(m);
}
However, my compiler barfs at the line:-
tmp.owner = this;
Error is:
[BCC32 Error] Unit7.cpp(30): E2034 Cannot convert 'BaseList<MyItem> * const' to 'MyList *'
It's like "this" has somehow become const, but I can't see why. Compiler is Codegear C++Builder 2009.
I admit I'm not 100% happy using templates, so I'm unsure if this is my problem or the compilers. The same code without template use compiles fine, but obviously that's not what I want, as I have several item/list classes that want to work this way.
Also, is there a better technique that would avoid having all the "owner" pointers in each item?
EDIT: I think I stripped the example down too far: "MyList" actually introduces new methods, which "MyItem" must then access through the "owner" pointer.
SUMMARY: Thanks for all comments and answers. As the accepted answer says, the problem is simply one of type incompatibility between pointer to a BaseList vs. MyList.
The issues raised about deriving from STL containers and alternative designs are also helpful, but the solution I've used is essentially identical to Luc Touraille's one below.
|
At line 30, "this" is a pointer to a BaseList<MyIteM>, not a MyList. You can substitute a class with a derived one, but not the other way around.
You can either typedef MyList to be a BaseList<MyItem>, like so:
typedef BaseList<MyItem> MyList
or let MyItem derive from Item<BaseList<MyItem> > instead.
When you derive from a type, you create a different type. When you typedef, you create an alias for that type. So when you typedef the compiler will accept this.
|
915,312
| 915,467
|
Different ways of exiting a process in C++
|
There are various ways of exiting a process:
e.g.: ExitProcess, ExitThread (from the main thread), exit, abort, return from main, terminate.
I'd like to know the effects each method has on static/global/automatic object destruction.
For example, I have a project that crashes (probably due to some deallocation error) when ExitProcess is called, but not when exit() is called. (related to this question, incidentally).
So basically I'd like to know under which circumstances deallocation of the above objects occurs, and in what order (For VC++).
|
In short: The only totally safe thing to do is to allow main(), or your thread function, to return.
The C++ standard guarantees (3.6.3/1, 18.3) that destructors for global objects (including static objects) will be called if exit() is called, however it explicitly states that destructors for local variables will not be called in this case. exit() will call any functions registered with atexit(), and will also flush and then close any open stdio streams (including at least stdin, stdout, stderr).
Calling abort() is guaranteed not to call local or global destructors. Nor will it call functions registered with atexit() or flush stdio streams.
Calling any Win32 primitive such as ExitProcess() or ExitThread() will certainly not call destructors for local variables, and will almost certainly not call any destructors for global objects, or any functions registered with atexit(). Calling these functions directly in a C++ program is not advised -- basically, these Win32 functions and the C++ runtime library know nothing about each other. In fact, even the MSDN documentation for ExitThread() advises that C++ programs should return from the thread function instead of calling ExitThread().
(It is theoretically possible that the runtime library has specially arranged for ExitProcess() to call global object destructors -- this could be done by always loading a specific DLL whose entry point function will perform these calls, since ExitProcess() will call the entry point function for each loaded DLL with DLL_PROCESS_DETACH -- however to my knowledge, no implementation does this.)
|
915,445
| 915,550
|
How to create a structure which contains a list of itself?
|
I want to create a structure which contains a list of same structure like this:
#include <list>
struct Url
{
CString strUrl;
std::list<Url> children;
};
int main()
{
Url u1, u2;
u1.children.push_back(u2);
}
This code is not compiling. But when I replace std::list with std::vector it is working fine. How can I make this working with std::list?
Output window contains the following error.
c:\program files\microsoft visual studio\vc98\include\list(29) : error C2079: '_Value' uses undefined struct 'Url'
E:\test\Test.cpp(23) : see reference to class template instantiation 'std::list<struct Url,class std::allocator<struct Url> >' being compiled
c:\program files\microsoft visual studio\vc98\include\functional(185) : error C2079: 'value' uses undefined struct 'Url'
c:\program files\microsoft visual studio\vc98\include\list(285) : see reference to class template instantiation 'std::binder2nd<struct std::not_equal_to<struct Url> >' being compiled
E:\test\Test.cpp(23) : see reference to class template instantiation 'std::list<struct Url,class std::allocator<struct Url> >' being compiled
|
If you need a workround for what seems to be a VC6 bug, create the list dynamically:
#include <list>
#include <string> // I don't use MFC
struct Url
{
std::string strUrl;
std::list<Url> * children;
Url() {
children = new std::list <Url>;
}
~Url() {
delete children;
}
};
int main()
{
Url u1, u2;
u1.children->push_back(u2);
}
Some have asked why lists of the same type as members are allowed (and in my view they are) when
Url array[5];
for example as a member would not be. I can't find anything in the standard either, but sizeof( std:;list <T>) is not dependent on the thing it is a list of. Suppose list was implemented as (some pseudo C++ here):
list <T> {
listEntry <T> * first;
};
then there is no unknown size to deal with. Consider the following minimal code that addresses the questioners problem:
template <typename T> struct A {
};
struct B {
A <B> b;
};
I can't see any possible reason that this should not be legal.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.