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 mat... | 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 ... |
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 ... |
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 num... | 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 e... |
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 implemen... | 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.as... |
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 00000... | 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 ... | 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 b... | 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 platfo... |
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_N... | 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 ... | 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 let... |
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 ... | 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. Becau... | 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 ... |
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 ... | 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 ap... |
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... | 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 tha... | 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)).... |
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 '*' t... | 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 t... |
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 C... |
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[] = {"r... | 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)... |
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... |
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() a... | 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() ... |
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... | 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 y... |
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->setAutoExclusiv... | 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->addBu... |
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; }
... | 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 ... |
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 someth... | 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 functio... |
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 G... | 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 suppos... |
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);... |
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, s... | 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 lis... |
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;
... | 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... |
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 WebSer... | 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 t... | 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 b... | 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 co... | 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 fa... |
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 metho... | 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. I... |
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 ... | 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... | 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 uno... |
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
};
};
... | 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
{
... |
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'... | 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 th... |
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 be... | 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 wr... |
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 faile... | 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... |
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... | 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 ... | 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 whit... |
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;
}
};
templat... | 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 )
... |
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 ... | 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 oper... |
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 acco... |
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 ... | 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;
HR... |
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 ... | 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... |
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 be... | 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", c... |
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, ... | 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 ... |
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 i... | 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... |
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... | 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 mini... |
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 tha... | 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 els... | 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 fi... |
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... | 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 bo... |
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... | 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 sepe... |
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'... | 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 pee... | 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 m... |
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 ... | 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) i... |
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 som... | 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, an... |
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 t... | 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 ques... | 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... |
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... | 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 i... |
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... |
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 do... |
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 work... | 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... | 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 specialize... |
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 u... | 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 gua... |
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 w... | 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 ... | 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 de... | 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, 25... | 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 fun... |
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 ... | 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() fu... |
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) c... | 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: f... |
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... | 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 t... | 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 applica... |
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 ... | 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 = "..." +... |
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(coll... | 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 tem... |
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 invok... | 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 (eve... |
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 guaran... | 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 "bett... |
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 thi... | 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, y... |
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).... | 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... |
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 ... |
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 pre... | 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 funct... |
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 h... | 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 f... |
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... | 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,... |
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... | 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.
... | 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 als... |
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 ... | 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 f... |
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) wh... | 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... |
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. H... | 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;
}
};
in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.