question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,024,351 | 1,024,500 | mixing C and C++ file operations | I am writing a file splitting program, to assist with using large files with iPod notes. I want to use tmpfile() in cstdio but it returns a file* not an fstream object. I know it's not possible in standard C++ but does anyone know any libraries that work well with the standard that have the ability to convert a FILE* t... | If all you want is a temporary file, use tmpnam() instead. That returns char* name that can be used for a temporary file, so just open a fstream object with that name.
Something like:
#include <cstdio>
#include <fstream>
...
char name[L_tmpnam];
tmpnam(name);
//also could be:
//char *name;
//name = tmpnam(NULL);
st... |
1,024,361 | 1,024,395 | Is using goto a legitimate way to break out of two loops? | I am solving problem 9 on the Project Euler. In my solution I use a "goto" statement to break out of two for loops. The Problem is the following:
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean ... | return is a "structured" goto which many programmers find more acceptable! So:
static int findit(int sum, int* pa, int* pb, int* pc)
{
for (int a = 1; a<sum; a++) {
for (int b = 1; b < sum; b++) {
int c = sum-a-b;
if (a*a+b*b == c*c) {
*pa = a; *pb = b; *pc = c;
... |
1,024,504 | 1,024,641 | Profiling C++ with Google Perf tools and Dynamic Libraries | I'm trying to profile a C++ application, that I did not write, to get a sense for where the major computation points are. I'm not a C++ expert and even less so C++ debugging/profiling expert. I believe I am running into a (common?) problem with dynamic libraries.
I compile link to Google CPU Profiler using (OS X, G++... | This error was caused by jags being a shell script, that subsequently called profilable code.
pprof /usr/local/bin/REAL_EXEC jags.prof
fixes the problem.
|
1,024,648 | 1,024,655 | Retrieving a c++ class name programmatically | I was wondering if it is possible in C++ to retrieve the name of a class in string form without having to hardcode it into a variable or a getter. I'm aware that none of that information is actually used at runtime, therefor it is unavailable, but are there any macros that can be made to create this functionality?
Edit... | You can use typeid:
#include <typeinfo>
std::cout << typeid(obj).name() << "\n";
However, the type name isn't standardided and may differ between different compilers (or even different versions of the same compiler), and it is generally not human readable because it is mangled.
On GCC and clang (with libstdc++ and li... |
1,025,077 | 1,025,091 | Visual studio release build | I'm trying to generate a release build for a C++ application that I've written. The application runs fine (debug & release) when you run it from within VS2008; but when you run the executable it crashes nearly every single time.
Now, is there a hack so I can run this application as a standalone application without hav... | In short, no.
you will have to find the bug, if it works within VS, then I'd hazard a guess that it is a timing issue, possibly you're overwriting shared thread data, this would be less likely (though still possible to see) inside VS as its being run in a debug environment which slows it down a bit.
If you want help fi... |
1,025,166 | 1,025,170 | Choice of language for portable library | I want to write a library which will be dynamically linked from other programs running on modern operating systems like Windows, Linux and OS/X (i.e. it will be deployed as a .dll or .so module).
What is the most appropriate language in that case? Should I stick with plain C? Or is C++ also ok?
| You can use either C or C++ for the implementation, but I would recommend to define the interface in pure C. It will be much easier to integrate.
|
1,025,707 | 1,025,718 | Getting a class/struct object from the member pointer | I have C++ structure as
struct myStruct {
int a;
int b;
int c;
};
myStruct b;
int *ptr = &b.c;
How can I get myStruct object back from ptr?
(I know I can do this using pointer arithmatic like container_Of() in C. Basically something like
reinterpret_cast<myStruct*>(reinterpret_cast<char *>(ptr) - offset... | There's certainly no recommended way, as doing this is definitely not recommended at all in C++. This is one of those questions where the correct answer has to be "Don't do that!"
The whole reason for using C++ instead of C is that you want to encapsulate the structure of data inside classes with sensible operations de... |
1,025,927 | 1,025,937 | Modifying a C string: access violation |
Possible Duplicates:
Why does simple C code receive segmentation fault?
Modifying C string constants?
Why does this code generate an access violation?
int main()
{
char* myString = "5";
*myString = 'e'; // Crash
return 0;
}
| *mystring is apparently pointing at read-only static memory. C compilers may allocate string literals in read-only storage, which may not be written to at run time.
|
1,025,941 | 1,025,962 | Any way to detect whether the pointer points to array? | Is there any way to detect, whether the pointer points to array in C++? My problem is that I want to implement a class, that becomes the owner of the array. My class is initialized with the pointer and I would like to know, whether the pointer is really an array pointer. Here is the simplified code:
class ArrayOwner {
... | No, unfortunately not. C++ RTTI does not extend to primitive types.
|
1,026,042 | 1,026,182 | When implementing operator[] how should I include bounds checking? | First of all I apologize for the long lead up to such a simplistic question.
I am implementing a class which serves as a very long 1 dimensional index on a space filling curve or the n-tuple representing the Cartesian coordinate that index corresponds to.
class curvePoint
{
public:
friend class curveCalculate;
... | The easiest solution is to do as C++ itself does. This limits the amount of surprises that your users will experience.
C++ itself is fairly consistent. Both the built-in [] on pointers and std::vector::operator[] have undefined behavior if you use an out-of-bound array index. If you want bounds checking, be explicit an... |
1,026,136 | 1,741,462 | Namespaces in C++ header files | I like the concept of C++ namespaces, because they help to keep the source code concise while avoiding name conflicts. In .cpp files this works very well, using the "using namespace" declaration. However, in header files this cannot be used, as it "breaks open" the namespace, meaning that the "using namespace" not only... | No, it can't be done :(
|
1,026,190 | 1,026,212 | What is difference between my atoi() calls? | I have a big number stored in a string and try to extract a single digit. But what are the differences between those calls?
#include <iostream>
#include <string>
int main(){
std::string bigNumber = "93485720394857230";
char tmp = bigNumber.at(5);
int digit = atoi(&tmp);
int digit2 = atoi(&bigNumber.at(... | It is all more or less explicable.
int main(){
std::string bigNumber = "93485720394857230";
This line copies the single character '5' into the character variable. atoi will convert this correctly. atoi expects that the string parameter is a valid 0 terminated string. &tmp is only a pointer to the character variabl... |
1,026,693 | 1,047,430 | How can I obtain a LaVectorDouble object which is a submatrixview of a LaGenMatDouble? | We are using Lapack++ for our matrix calculations. One of the features is the use of submatrixviews; objects that refer to the same spot in memory.
Example:
LaGenMatDouble W = LaGenMatDouble::rand(3,4);
LaGenMatDouble A = W(LaIndex(0,2), LaIndex(1,3));
LaGenMatDouble b = W(LaIndex(0,2), LaIndex(0,0));
A and b ar... | The answer is to use the ref function.
LaVectorDouble b;
b.ref(W(LaIndex(0,2), LaIndex(0,0)));
All other functions are copying (like constructor, = and copy) or giving the wrong class (like the constructor with indices). The ref function is referencing to memory.
|
1,026,769 | 1,026,779 | Creating arrays on the heap and addressing them with pointers | I'm having trouble understanding the following bit of code that I was hoping would create an array on the heap and fill it with the characters 9 down to 0 (I know I could just index the array like a normal stack array with [] notation to do this but I'm doing it this way to try to understand pointers in more depth):
in... | The line
ptrHeapArray++;
in your first for loop increments the pointer, such that it doesn't point to the beginning of the array anymore.
The line
int *ptrHeapArray = new int[10];
allocates the memory for 10 integers and points ptrHeapArray to the beginning of that memory. In your for loop you then move this pointer.... |
1,026,990 | 1,027,052 | How to pass two parameters when using std::mem_fun? | Lets say I have hierarchy like this (This is just a test program. Please do not point anything related to memory leaks, destructor is not virtual etc):
class I
{
public:
virtual void fun(int n, int n1) = 0;
};
class A : public I
{
public:
void fun(int n, int n1)
{
std::cout<<"A::fun():" <<n<<" and ... | You could create your own functor like this:
class Apply
{
private:
int arg1, arg2;
public:
Apply(int n, int n1)
: arg1(n), arg2(n1)
{}
void operator() (I* pI) const
{
pI->fun(arg1, arg2);
}
};
int main ()
{
// ...
std::for_each(a.begin(), a.end(), Apply(n, n1));
}
or use boost::bin... |
1,027,128 | 1,027,150 | What is a Map and how would I use one in C++? | What is a Map? How would I create and use one in C++?
| If you mean std::map, it stores pairs of values. In each pair, the first value is called the key, and can be used to quickly look up the associated other value.
You can write:
std::map<std::string, int> ages;
ages["Fred"] = 52;
ages["Sue"] = 31;
std::cout << "Fred's age is " << ages["Fred"] << std::endl;
|
1,027,179 | 1,027,210 | Displaying SVG in OpenGL without intermediate raster | I have some simple SVG artwork (icon and glyph kind of things) which I want to display in an OpenGL app (developing in C++ on Debian, using Qt).
The obvious solution is to use the ImageMagick libs to convert the SVGs to raster images and texture map them onto some suitable polygons (or just use good old glDrawPixels).
... | Qt can do this.
QSvgRenderer can take an SVG and paint it over a QGLWidget
Its possibly you'll need to fiddle around with the paintEvent() abit if you want to draw anything else on the QGLWidget other than the SVG.
|
1,027,416 | 1,029,084 | How can I prevent the need to copy strings passed to a avr-gcc C++ constructor? | In the ArduinoUnit unit testing library I have provided a mechanism for giving a TestSuite a name. A user of the library can write the following:
TestSuite suite("my test suite");
// ...
suite.run(); // Suite name is used here
This is the expected usage - the name of the TestSuite is a string literal. However to preve... | What if you provide two overloaded constructors?
TestSuite(const char* name) ...
TestSuite(char* name) ...
If called with a const char*, then the constructor could make a copy of the pointer, assuming that the string will not go away. If called with a char*, the constructor could make a copy of the whole string.
Note ... |
1,027,422 | 1,898,216 | Visual Studio 2005 C++ Compiler slower that Visual Studio 6 Compiler? | One of our old C++ projects is still with Visual Studio 6. Once a year I try to convert it in to a higher Visual Studio Version but it's not easy because not all the code is written by us.
Anyway, I finally succeeded in converting the project to VS2005 after fixing a few hundred lines of code. But compiling the projec... | VS2005 produces more optimized code and thus has to spend extra time figuring out how to make it faster.
|
1,027,435 | 1,027,468 | Explicitly Linking to Classes in DLL's | I have a class that is currently in a .lib file:
class __declspec(dllexport) ReportData {
public:
list<FileData *> ReportFileData;
list<SupressionData *> ReportSupressionData;
static char *ClientName;
static char *DataRecieved;
std::string GenFileConfTemplate();
~Repor... | You can do this the way COM does it:
Export a CreateInstance() function.
Pass a void** and unique identifier to CreateInstance().
Your consuming DLL calls LoadLibrary() on the library DLL and calls CreateInstance().
CreateInstance() does the new ReportData and returns it in the void** out param.
Edit:
Something like... |
1,027,585 | 1,027,707 | Performing an operation at an interval | I want to perform the action at a certain timeout, like fire an
event. I figured out how to do every n number of seconds, but not 1.5
seconds. Here is what I have. Please suggest how to handle my case:
void Publish()
{
static int local_time=time(NULL);
int current_time = time (NULL);
if((current_time+PU... | This returns the wall time since the application started in millisecs. It uses the machines clock so it is quite possible that changing the clock's time while the app is running will confuse it. In your case I would add a schedule time to my event object and fire when schedule time <= msec()
clock_t msec() {
sta... |
1,027,610 | 1,027,668 | Using STL algorithms, is it better to pass a function pointer or a functor? | Which of these 2 methods is better and why?
Method 1:
void fun(int i) {
//do stuff
}
...
for_each(a.begin(), a.end(), fun);
Method 2:
class functor {
public:
void operator()(int i);
};
...
for_each(a.begin(), a.end(), functor());
Edit: Should have formulated it this way, in what situation is one of the above me... | Functors may (and will) be trivially inlined – this isn't done for regular function pointers.
Thus, functors have a real performance benefit which may be huge in tight loops. Furthermore, functors are generally more easily composable and in particuler play nicer with the STL: std::bindx doesn't work on function pointer... |
1,027,724 | 1,027,756 | C++ function overriding | I have three different base classes:
class BaseA
{
public:
virtual int foo() = 0;
};
class BaseB
{
public:
virtual int foo() { return 42; }
};
class BaseC
{
public:
int foo() { return 42; }
};
I then derive from the base like this (substitute X for A, B or C):
class Child : public BaseX
{
public:
int... | In the derived class a method is virtual if it is defined virtual in the base class, even if the keyword virtual is not used in the derived class's method.
With BaseA, it will compile and execute as intended, with foo() being virtual and executing in class Child.
Same with BaseB, it will also compile and execute as in... |
1,027,785 | 1,411,794 | Converting a project from C++ to C# | I've got a medium scale project (a turn-based game) that's currently written in C/C++. Only one person is working on it. It will complie with /clr, although I haven't tried /clr:pure.
I'm looking for advice on the overall process of converting it to C#.
It's mainly C with a thin veneer of C++ on it (C with static/singl... | I found out that CodeRush (which I already own) has a 'smart paste' operation which does a reasonable job of converting what can be converted. There's also a CR_Paste add-in on googleplex which does something similar (the CR_Paste add-in may not require Coderush, only the free DXCore application).
Since I'll have full ... |
1,027,988 | 1,028,007 | How do you manage logging performance? | We have a message processing system where low latency is critical. Recently, I found that while we keep a high rate through our system we are seeing some "outliers." (Messages that take much longer then they should) When we removed logging our systems show none of these outliers.
Right now our logging is basically... | I guess it's OS dependent to some extent.
On win32, our logging subsystem simply queues the messages up for a logging thread which handles the disk I/O.
This decouples disk I/O performance from time-critical threads, and gives us good control over exactly how and when the queue gets locked.
|
1,028,341 | 1,069,350 | Making an index-creating class | I'm busy with programming a class that creates an index out of a text-file ASCII/BINARY.
My problem is that I don't really know how to start. I already had some tries but none really worked well for me.
I do NOT need to find the address of the file via the MFT. Just loading the file and finding stuff much faster by sea... | It seems to me that all your class needs to do is store an array of pointers or file start offsets to the key locations in the file.
It really depends on what your Key locations represent.
I would suggest that you access the file through your class using some public methods. You can then more easily tie in Key locatio... |
1,028,437 | 1,028,463 | Why Switch/Case and not If/Else If? | This question in mainly pointed at C/C++, but I guess other languages are relevant as well.
I can't understand why is switch/case still being used instead of if/else if. It seems to me much like using goto's, and results in the same sort of messy code, while the same results could be acheived with if/else if's in a muc... | Summarising my initial post and comments - there are several advantages of switch statement over if/else statement:
Cleaner code. Code with multiple chained if/else if ... looks messy and is difficult to maintain - switch gives cleaner structure.
Performance. For dense case values compiler generates jump table, for sp... |
1,028,443 | 1,028,511 | Global const string& smells bad to me, is it truly safe? | I'm reviewing a collegue's code, and I see he has several constants defined in the global scope as:
const string& SomeConstant = "This is some constant text";
Personally, this smells bad to me because the reference is referring to what I'm assuming is an "anonymous" object constructed from the given char array.
Syntac... | It's completely legal. It will not be destructed until the program ends.
EDIT: Yes, it's guaranteed:
"All objects which do not have dynamic
storage duration, do not have thread
storage duration, and are not local
have static storage duration. The
storage for these objects shall last
for the duration of the ... |
1,028,531 | 1,028,835 | Returning a new object along with another value | I want to return two values, one of which is a new object. I can do this using std::pair:
class A {
//...
};
std::pair<A*, int> getA()
{
A* a = new A;
//...
}
To make the code exception-safe, I would like to do:
std::pair<std::auto_ptr<A>, int> getA()
{
std::auto_ptr<A> a(new A);
//...
}
But this wo... | Just create a new class and return that class
class Result
{
A* a;
int i;
public:
Result( A*a, int i ) : a(a), i(i) {
}
~Result() {
delete a;
}
// access functions, copy constructor, ...
};
Result getA() {
//...
return Result(new A, intValue);
}
|
1,028,636 | 1,030,858 | CGAL: erroneous Delaunay result? | The result of my Delaunay triangulation on 1000 unifomally random points doens't look right at all (see image). Some points seem to belong an abnormally high number of triangles... Any idea?
Detail: CGAL 3.4, windows XP
This is the types I used:
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typede... | Are you using a regular rather than a Delaunay triangulation?
You are using the following, right?
CGAL::Delaunay_triangulation_2<Traits,Tds>
http://www.cgal.org/Manual/3.4/doc_html/cgal_manual/Triangulation_2_ref/Class_Delaunay_triangulation_2.html#Cross_link_anchor_1152
|
1,028,785 | 1,028,877 | alloca() of a templated array of types: how to do this? | I have a smart pointer type, and would like to construct an object that takes a pointer of that type and a count (dynamically calculated at runtime) and allocates enough memory from the stack to hold that many instances of the object the smart pointer points to. I can't seem to find quite the right syntax to achieve th... | Never mind, worked it out; the trick was to combine both approaches:
template<typename WrappedT>
SomeObject<typename WrappedT::Type> _MakeSomeObject
( void *_buffer, WrappedT _pointer, int _runtimeCount )
{
return SomeObject<typename WrappedT::Type>
( _buffer, _pointer, _runtimeCount );
}
template<type... |
1,029,055 | 1,029,072 | Trouble compiling a header file in VC++ | I just reorganized the code for a project and now I'm getting errors I can't resolve. This header is included by a .cpp file trying to compile.
#include "WinMain.h"
#include "numDefs.h"
#include <bitset>
class Entity
{
public:
Entity();
virtual ~Entity();
virtual bitset<MAX_SPRITE_PIXELS> getBitMask();
... | Declare the bitset as std::bitset<MAX_SPRITE_PIXELS>.
|
1,029,192 | 1,029,208 | When HeapCreate function is used or in what cases do you need a number of heaps? | Windows API has a set of function for heap creation and handling: HeapCreate, HeapAlloc, HeapDestroy and etc.
I wonder what is the use for another heap in a program?
From fragmentation point of view, you will get external fragmentation where memory is not reused among heaps. So even if low-fragmentation heaps are used... | One use case might be a long-running complex process that does a lot of memory allocation and deallocation. If the user wants to interrupt the process, then an easy way to clean up the memory currently allocated might be to have everything on a private heap and then simply destroy the heap.
I have seen this technique u... |
1,029,334 | 1,029,615 | How to use a single namespace across files? | I have a C++ project (VC++ 2008) that only uses the std namespace in many of the source files, but I can't find the "right" place to put "using namespace std;".
If I put it in main.cpp, it doesn't seem to spread to my other source files. I had it working when I put this in a header file, but I've since been told that'... | You generally have three accepted options:
Scope usage (std::Something)
Put using at the top of a source file
Put using in a common header file
I think the most commonly accepted best practice is to use #1 - show exactly where the method is coming from.
In some instances a file is so completely dependent on pulling s... |
1,029,401 | 1,035,816 | C++ overflow with new keyword debugging | I'm having a tricky debugging issue, perhaps due to my lack of understanding about how c++ manages memory. The code is too long to post, but the essential setup is as follows:
global_var = 0;
int main() {
for(i = 0; i < N; ++i) {
ClassA a;
new ClassB(a); // seems to be problem!
}
}
For some N, global_var ... | After much exploration, this behavior turned out to be due to a bug in the underlying class of global_var. There was a subtle bug in the way global and static memory allocation was being done.
|
1,029,559 | 1,029,584 | java, System.loadlibrary("someDLLFile") gets unstatisfied link error | I have written some JNI hooks into a C++ library and created some DLL files for my java server project. Lets say the DLL and jar files are in the same folder under "C:/server"
I am accessing these DLL files using:
System.loadLibrary("someDLLFile");
in the class that needs the C++ code.
The problem I am running into is... | It works because the DLL (or a DLL it depends on, i.e. msvcr90.dll or something) are in the PATH on your machine, but not on the other one.
Either set PATH env-var or the java.library.path property to contain the dir with your file, or store your dll where java finds it by default (Many options here, depending on deplo... |
1,029,711 | 1,029,717 | MFC: OnInitialUpdate function of a CFormView-derived class | My CFormView-derived class is structured as follows:
class FormViewClass : public CFormView
{
...
FormViewClass();
void Initialize();
virtual void OnInitialUpdate();
...
};
Ideally, I would like to call the Initialize() function in the body of the constructor as follows:
FormVie... | I think you're right to do it the way you're doing it.
In general, I would try to initialise things as early as possible (but no earlier 8-) so doing non-GUI stuff in the constructor, and GUI stuff in OnInitialUpdate makes sense.
(If OnInitDialog existed for CFormView, that would probably be a better place than OnIniti... |
1,029,743 | 1,029,751 | What does "(void) new" mean in C++? | I've been looking at a Qt tutorial which uses a construction I haven't seen before:
(void) new QShortcut(Qt::Key_Enter, this, SLOT(fire()));
(void) new QShortcut(Qt::Key_Return, this, SLOT(fire()));
(void) new QShortcut(Qt::CTRL + Qt::Key_Q, this, SLOT(close()));
I've tried this without the (void) and it still comp... | Casting an expression to (void) basically tells the compiler to ignore the result of that expression (after computing it).
In your example, each of the expressions (per statement/line) is dynamically allocating memory via the new operator - and since new returns a pointer (address) to the memory, the usual practice is ... |
1,030,100 | 1,032,586 | How can I make rdoc properly read method arguments from my c extension? | all, I'm using rdoc to generate documentation for my Ruby code which contains C-extensions, but I'm having problems with my method arguments. Rdoc doesn't parse their names correctly and instead uses p1, p2 etc.
So, first off, my extensions are actually compiled as C++ so I have to use function definitions that look l... | RDoc is completely clueless about argument names in C extensions*. This is how RDoc compiles the string of arguments:
meth_obj.params = "(" + (1..p_count).map{|i| "p#{i}"}.join(", ") + ")"
Changing your source formatting won't help.
To improve your documentation, you could use the call-seq directive. You can specify o... |
1,030,190 | 1,030,205 | XML Representation of C++ Objects | I'm trying to create a message validation program and would like to create easily modifiable rules that apply to certain message types. Due to the risk of the rules changing I've decided to define these validation rules external to the object code.
I've created a basic interface that defines a rule and am wondering wh... | Personally, for small, easily modifiable XML, I find TinyXML to be an excellent library. You can make each class understand it's own format, so your object hierarchy is represented directly in the XML.
However, if you don't think you need XML, you might want to go with a lighter storage like yaml. I find it is much eas... |
1,030,274 | 1,030,308 | Is there a way to scan for when people forget to call the base class version of a virtual? | I just fixed a memory leak caused by someone forgetting to call the superclass's OnUnload in their override of it. The superclass version frees some resources (as does its superclass).
Are there external static analysis tools, or at least some kind of runtime trick I can do to detect this? With the ability to make an e... | A runtime "trick" you could use is to assert in the destructor of the base class if the constraint you are looking for has failed. Assuming the instance is actually destroyed and not leaked, this will tell you at the time the object is destroyed if the contract was correctly followed.
|
1,030,349 | 1,030,363 | Permutations and Combinations - Runtime Failure | This program takes 2 numbers from user input, asks them whether they'd like to find out the permutations or combinations, and then outputs the result. Here's the code.
#include "std_lib_facilities.h"
int permutation(int first, int second)
{
int top_fac;
int bottom_fac;
for (int i = first-1; i >= 1; --i)
top_fac *=... | You're not initializing the local variables top_fac and bottom_fac inside of your functions. Unlike other languages, local variables are NOT initialized to anything in particular in C or C++. The values that they receive are whatever garbage happens to be on the stack when you call the function. You should explicitl... |
1,030,440 | 1,030,459 | Effective way to make a system tray application | This is my first post on Stack Overflow and I'm just wondering on the options of making a system tray application. The application would run primary from the system tray while still operating, and could be brought up into a window when clicked on. It is also needed to have some support for global keystroke tracking, to... | Java 6 has new functionality which allows for the creation of applications which use the system tray.
The New System Tray Functionality in Java SE 6 article goes into the details, and provides some sample code as well.
The newly added SystemTray and TrayIcon classes of the java.awt package can be used to add icons to t... |
1,030,567 | 1,033,085 | Threading issues in C++ | I have asked this problem on many popular forums but no concrete response. My applciation uses serial communication to interface with external systems each having its own interface protocol. The data that is received from the systems is displayed on a GUI made in Qt 4.2.1.
Structure of application is such that
When ap... | First off all don't make the Systems singletons. Use some kind of Context Encapsulation
for the different system.
If you ignoe this advice and still want to create "singletons" threads at least use QApplication::instance(); as the parent of the thread and put QThread::wait() in the singleton destructors otherwise yo... |
1,030,608 | 1,030,634 | Summing struct members inside a vector | Consider the following:
typedef struct {
int a;
int b;
int c;
int d;
} ABCD;
typedef std::vector<ABCD> VecABCD;
Say I wanted to add up every 'a' member in a vector of type VecABCD. Easy! I just loop through the vector, and sum as I go.
int CalcSumOfA(const VecABCD &vec)
{
int sumOfA = 0;
Vec... | STL summations can be done with std::accumulate
#include <functional>
accumulate(v.begin(), v.end(), 0, bind(plus<int>(), _1, bind(&ABCD::a, _2)))
If you wanted this to be more generic, you could take a tr1::function to the member you want to bind:
int sum_over_vec(const vector<ABCD>& v, const tr1::function<int (cons... |
1,030,829 | 1,036,129 | gprof reports no time accumulated | I'm trying to profile a C++ application with gprof on a machine running OSX 10.5.7.
I compile with g++ in the usual way, but using -pg flags, run the application and try to view the call graph with gprof.
Unfortunately my call graph contains all zeroes for all time columns. The values in the "called" columns have reaso... | I thought I might share this Apple mailing list discussion which I recently ran across.
The behaviour described here is exactly what I am experiencing.
It looks like gprof has been broken on OSX for quite some time.
I've resorted to Shark which has been helpfully suggested by Dave Rigby.
Thanks!
|
1,030,927 | 1,030,981 | Dynamic Binding in C++ | Why does the derived class have to declare its methods as virtual for dynamic binding to work even though the methods of the base class are declared virtual?
| It doesn't have to. If a method is declared virtual in a base class, overriding it in a derived class makes the overriding function virtual as well, even if the virtual keyword is not used.
|
1,031,301 | 1,031,676 | Can I implement the Factory Method pattern in C++ without using new? | I'm working in an embedded environment (Arduino/AVR ATMega328) and want to implement the Factory Method pattern in C++. However, the compiler I'm using (avr-gcc) doesn't support the new keyword. Is there a way of implementing this pattern without using new?
| Since the AVR compiler is based on the gcc compiler, it is very likely to support the new keyword. What exactly is the error you're getting. I'm guessing it's a link/compiler error along the lines of an undefined function, namely, operator new. There is a difference between the new operator and operator new, the first ... |
1,031,462 | 1,031,467 | How do i write over the last line in the console? | I want to show a progress bar (like wget) how do i keep writing to the last line in the console?
Windows 7
vis 2005
c++
| with carriage-return ("\r") you can jump back to the beginning of the current line.
This will only work for terminals which have support for this feature.
After you jumped back you can just print your new status-line.
|
1,031,543 | 1,031,605 | What is the full list of actions performed by placement new in C++? | In this question creating a factory method when the compiler doesn't support new and placement new is discussed. Obviously some suitable solution could be crafted using malloc() if all necessary steps done by placement new are reproduced in some way.
What does placement new do - I'll try to list and hope not to miss an... | Placement new does everything a regular new would do, except allocate memory.
I think you've essentially nailed what happens, with some minor clarifications:
obviously the constructor of the class itself is called as well
vtable pointers are initialized as part of constructor calls, not separately. An implication of t... |
1,031,772 | 1,034,366 | Public key or Diffie-Hellman Key Exchange Algorithm | Consider and client server scenario and you got two options:
You can include Server's Public Key
in Client and perform the exchange.
You can use Diffie Hellman
KeyExchange Algorithm to handshake
and then exchange the key.
Which one is more secure way?
also if public key will come from store say from Client CA store? ... | Don't.
If you need to solve this kind of problem in production code, have an expert do it. There are so many subtle pitfalls in cryptography that chances are you will come a cropper.
|
1,031,800 | 1,031,840 | Implementing complex inheritance in C++ | I have the following existing classes:
class Gaussian {
public:
virtual Vector get_mean() = 0;
virtual Matrix get_covariance() = 0;
virtual double calculate_likelihood(Vector &data) = 0;
};
class Diagonal_Gaussian : public Gaussian {
public:
virtual Vector get_mean();
virtual Matrix get_covariance();
virtu... | Looks good, I think this is a pretty classic implementation of the Adapter pattern. Just don't forget to declare a virtual destructor for your Gaussian class. As for the disadvantages.
The way Java class library deal with the dummy method problem is to create a dummy class that provides empty implementation for every... |
1,031,896 | 1,031,905 | Inline float to uint "representation" not working? | This is in C, but I tagged it C++ incase it's the same. This is being built with:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.220 for 80x86
if that makes any different
Why does this work?
(inVal is 0x80)
float flt = (float) inVal;
outVal = *((unsigned long*)&flt);
(results in outVal being 0x... | You're trying to take the address of a non-const temporary (the result of your (float) conversion) – this is illegal in C++ (and probably also in C). Hence, your code results in garbage.
In your first, working, code, you're not using a temporary so your code is working. Notice that from a standards point of view this i... |
1,031,924 | 1,032,028 | Does a Boost test suite exist? | I'm working on building the Boost platform for a currently unsupported toolchain. Obviously we'd like to verify that the compiler is building everything OK, so we've some measure of how successful the porting is going. However it's not immediately clear whether or not Boost has such a test suite, good ol' Google fails ... | Are you looking for the Boost regression test suite?
|
1,031,996 | 1,069,996 | wxWidgets wont update till mouse moves | I got a wxWidgets form with a progress bar on it and i update the progress from a thread using my own custom wxWidget event. This works fine except the fact is the form only shows the progress update when i move the mouse. I have tried adding Refresh() and Update() after the new progress value is set but with no luck.
... | I worked it out. Its because of SetTopWindow(); When i remove this line from my app all events are processed in due time.
|
1,032,021 | 1,032,049 | Is it possible to UAC elevate a process without starting another process | I was wondering if it is possible for a program to prompt the user with a UAC prompt to raise it's own privileges without starting another process.
All the examples I can find on the internet seem to ShellExecute "runas" which creates a new process with elevated privileges.
If this is not possible then my best solution... | No, you can't elevate an existing process. You're right - you have start a new elevated process and get that to do the work for you.
|
1,032,030 | 2,517,433 | 400.0 - Bad Request with MSXML2::IXMLHTTPRequestPtr | I'm trying to access an xml file over http. The address is similar to:
http://localhost/app/config/file.xml
When pasting this in a browser the xml is displayed as expected. In my software I am using:
MSXML2::IXMLHTTPRequestPtr rp;
...
rp->open( "GET" , "http://localhost/app/config/file.xml" );
and getting the followi... | I think I found your answer, you have to prefix the date with 0.
XmlHttpRequest with If-Modified since, webserver returns "400 Bad Request"
|
1,032,131 | 1,032,145 | manipulation of Vectors created with new | Can anyone help with this...
vector<unsigned int> *vVec = new vector<unsigned int>;
vVec .reserve(frankReservedSpace);
start = std::clock();
for(int f=0; f<sizeOfvec; f++)
{ //Populate the newly created vector on the heap
vVec .push_back(pArray[f]);
}
I'm gett... | vVec is a pointer to a vector. Therefore you should be using the indirection (->) operator rather than the dot (.)
vector<unsigned int> *vVec = new vector<unsigned int>;
vVec->reserve(frankReservedSpace);
start = std::clock();
for(int f=0; f<sizeOfvec; f++)
{ //Populate the newly created vector on the heap
vVec->... |
1,032,243 | 1,032,252 | Should I return std::strings? | I'm trying to use std::string instead of char* whenever possible, but I worry I may be degrading performance too much. Is this a good way of returning strings (no error checking for brevity)?
std::string linux_settings_provider::get_home_folder() {
return std::string(getenv("HOME"));
}
Also, a related question: wh... | Return the string.
I think the better abstraction is worth it. Until you can measure a meaningful performance difference, I'd argue that it's a micro-optimization that only exists in your imagination.
It took many years to get a good string abstraction into C++. I don't believe that Bjarne Stroustroup, so famous for ... |
1,032,973 | 1,036,945 | How to partially specialize a class template for all derived types? | I want to partially specialize an existing template that I cannot change (std::tr1::hash) for a base class and all derived classes. The reason is that I'm using the curiously-recurring template pattern for polymorphism, and the hash function is implemented in the CRTP base class. If I only want to partially specialize ... | There are two variants in the following code. You could choose more appropriated for you.
template <typename Derived>
struct CRTPBase
{
size_t hash() const {return 0; }
};
// First case
//
// Help classes
struct DummyF1 {};
struct DummyF2 {};
struct DummyF3 {};
template<typename T> struct X;
// Main classes
te... |
1,033,026 | 1,033,083 | Debugging in XCode as root | In my program I need to create sockets and bind them to listen HTTP port (80). The program works fine when I launch it from command line with sudo, escalating permissions to root. Running under XCode gives a 'permission denied' error on the call to binding function (asio::ip::tcp::acceptor::bind()).
How can I do debugg... | Update: For Xcode 4.5 and later, see this answer instead.
The only way I'm aware of to do what you're asking is to run Xcode as root.
>> sudo /Developer/Applications/Xcode.app/Contents/MacOS/Xcode
Once you're running as root, anything processes launched from Xcode will also run as root. Note, though, that if you cre... |
1,033,089 | 1,033,097 | Can I increment an iterator by just adding a number? | Can I do normal computations with iterators, i.e. just increment it by adding a number?
As an example, if I want to remove the element vec[3], can I just do this:
std::vector<int> vec;
for(int i = 0; i < 5; ++i){
vec.push_back(i);
}
vec.erase(vec.begin() + 3); // removes vec[3] element
It works for me (g++), bu... | It works if the iterator is a random access iterator, which vector's iterators are (see reference). The STL function std::advance can be used to advance a generic iterator, but since it doesn't return the iterator, I tend use + if available because it looks cleaner.
C++11 note
Now there is std::next and std::prev, whic... |
1,033,207 | 1,033,272 | What should I use instead of sscanf? | I have a problem that sscanf solves (extracting things from a string). I don't like sscanf though since it's not type-safe and is old and horrible. I want to be clever and use some more modern parts of the C++ standard library. What should I use instead?
| Try std::stringstream:
#include <sstream>
...
std::stringstream s("123 456 789");
int a, b, c;
s >> a >> b >> c;
|
1,033,395 | 1,033,435 | Disconnect a Remote Desktop session programmatically | How do I disconnect a Remote Desktop session programmatically in a C# or C++ application?
| Use WTSDisconnectSession.
|
1,033,515 | 1,522,987 | Error Message: "Resource ExperimentFrame.res not found" | I'm trying to create a frame VCL inside my project using factory pattern
something like this:
TFrame* newToolbarFrame =
FrameFactory::getInstance().createObject(toolbarFrameClassId);
When the factory creates the implementation class, I get an error message about missing resource file.
For example if I create an in... | TFrame is trying to perform DFM streaming of its design-time properties, but your app is not linking in the actual TFrameFooBar class's DFM into the executable's resources for TFrame to find at runtime.
|
1,033,584 | 1,033,598 | How to delete an array of pointers | I've been brushing up on my C++ as of late, and I have a quick question regarding the deletion of new'd memory. As you can see below i have a simple class that holds a list of FileData *. I created an array to hold the FileData objects to be pushed into the list. When ReportData is destructed I loop through the list an... | You don't. fileData is an automatic (stack) variable. You didn't allocate it with new, so you don't delete it.
[Edit: also I'm not sure, but I think you could face problems deleting those FileData objects from main.cpp, considering that they were allocated in some dll. Does the dll provide a deleter function?]
|
1,033,981 | 1,034,201 | Is there a problem with this usage of boost condition code? | Will this code ever wait on the mutex inside the producer's void push(data)?
If so how do I get around that?
boost::mutex access;
boost::condition cond;
// consumer
data read()
{
boost::mutex::scoped_lock lock(access);
// this blocks until the data is ready
cond.wait(lock);
// queue is ready
return data_fr... | When .wait() is called it will block the calling thread in your thread pool and release the mutex. It will return when someone calls notify_one() or notify_all(). Before the thread that was blocked returns though, it will re-acquire the mutex and unblock the thread in your thread pool.
So the call to void push(data... |
1,034,045 | 1,034,081 | How much memory should you be able to allocate? | Background: I am writing a C++ program working with large amounts of geodata, and wish to load large chunks to process at a single go. I am constrained to working with an app compiled for 32 bit machines. The machine I am testing on is running a 64 bit OS (Windows 7) and has 6 gig of ram. Using MS VS 2008.
I have th... | As much as the OS wants to give you. By default, Windows lets a 32-bit process have 2GB of address space. And this is split into several chunks. One area is set aside for the stack, others for each executable and dll that is loaded. Whatever is left can be dynamically allocated, but there's no guarantee that it'll be o... |
1,034,552 | 1,034,592 | Good datastructure for look up of an id mapping to set of elements (c++) | No boost, just plain STL please.
I have a class Foo* mapping to a set of pointers of class ID.
and I need to map a pointer to an instance of ID to a FOO class.
say I have this function:
void FindXXX(const ID* pID)
{
/*find the containing FOO class quickly, but not at expense of an ugly code*/
}
right now I map e... |
right now I map each ID* to FOO* thus
having something like that
map myMap; which I think is kind of
ugly and redundant.
I assume you have something like this:
map<ID*, Foo*> myMap;
Why would that be ugly?
|
1,034,606 | 1,038,045 | Is there any use for local function declarations? | Most C++ programmers like me have made the following mistake at some point:
class C { /*...*/ };
int main() {
C c(); // declares a function c taking no arguments returning a C,
// not, as intended by most, an object c of type C initialized
// using the default constructor.
c.foo(); ... | I've wanted local function declarations in C when I wanted to pass them as arguments to some other function. I do this all the time in other languages. The reason is to encapsulate the implementation of data structures.
E.g. I define some data structure, e.g. a tree or a graph, and I don't want to expose the details ... |
1,034,719 | 1,055,981 | Windows socket notification sink | What is the windows socket notification sink for? I am currently working with MFC socket and I think I have done something wrong since I get this message at windows shutdown. What could cause this?
Thank you.
Edit:
I am currently working with an application that needs to communicate via sockets. When I shutdown my comp... | An endpoint that you created was not properly closed. The Windows Socket Notification Sink is still running at shutdown because it believes it still needs to manage an endpoint.
Be sure you are properly disposing of all instances of socket classes that you create so that Windows cleans up and knows they no longer need ... |
1,034,904 | 1,034,943 | Initializing 2D int array in run-time | I got the code below from a C++ book, and I cannot figure out how the initialization works.
From what I can see, there is an outer for loop cycling trough the rows, and the inner loop
cycling trough the column. But its is the assignment of the values into the array that I do not understand.
#include <iostream>
using na... | (t*4)+i+1
Is an arithmetic expression. t and i are ints, the * means multiply. So for row 1, column 2, t = 1, i = 2, and nums[1][2] = 1x4+2+1 = 7.
Oh, forgot a couple things. First, the () is to specify the order of operations. So the t*4 is done first. Note that in this case the () is unnecessary, since the mult... |
1,035,096 | 1,035,195 | C++ hdr image i/o library (linux and windows) | I need to find/create a library that can load hdr images in many formats for use in opengl.
I have been using SDL_image, but it doesn't support hdr.
I don't want to use many different image libraries, so if there is one that supports a large amount (bmp, png, jpg, tiff, tga, hdr are the most important).
If there is non... | How about ImageMagick? You can install HDRI support, apparently. Looks like it can be used with openGL, though I'm not sure if that suits your needs.
|
1,035,278 | 1,035,287 | Is clickonce possible with regular c++ executable | I have a c++ console application which I would like to publish using clickonce.
When I run the mageui.exe tool and import the executable and dependent files to make an application manifest, it won't let me set the app.exe as the entry point. I can set the entry point, but when I click off the line and go to save, it cl... | Between the "assembly identity" and setting the processor architecture to MSIL, it seems like you're telling it that the entry point is into a .NET assembly of some kind.
Unfortunately, from cursory searching it seems you cannot deploy an unmanaged/native application with clickonce. The entry point must be managed.
You... |
1,035,389 | 1,035,399 | Getting the pid of my children using linux system calls in C++ | I have a process that interfaces with a library that launches another process. Occasionally this process gets stuck and my program blocks in a call to the library. I would like to detect when this has happened (which I am doing currently), and send a kill signal to all these hung processes that are a child of me.
I k... |
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp = popen("ps -C *YOUR PROGRAM NAME HERE* --format '%P %p'" , "r");
if (fp == NULL)
{
printf("ERROR!\n");
}
char parentID[256];
char processID[256];
while (fscanf(fp, "%s %s", pare... |
1,035,447 | 1,040,438 | Intellisense auto-complete is causing VC++ in Visual Studio 2005 SP1 to crash | UPDATE1: I have reinstalled Visual Studio and I am still having this problem. My guess is there is a problem with my environment.
Update2: Diving in.
I attached windbg to devenv and set a breakpoint in windbg for msenv!_tailMerge_WINMM_dll and traced through.
This is trying to load winmm.dll using the LoadLibrary API... | What a bizarre problem.
I finally figured it out using procmon from sysinternals:
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
My sounds were somehow changed to windows default sounds after a recent trip to IT. This caused visual studio to play a clicking sound when intellisense happens. In order to pl... |
1,035,657 | 1,035,713 | Seeking and reading large files in a Linux C++ application | I am running into integer overflow using the standard ftell and fseek options inside of G++, but I guess I was mistaken because it seems that ftell64 and fseek64 are not available. I have been searching and many websites seem to reference using lseek with the off64_t datatype, but I have not found any examples referenc... | fseek64 is a C function. To make it available you'll have to define _FILE_OFFSET_BITS=64 before including the system headers That will more or less define fseek to be actually fseek64. Or do it in the compiler arguments e.g.
gcc -D_FILE_OFFSET_BITS=64 ....
http://www.suse.de/~aj/linux_lfs.html has a great overviw of... |
1,035,666 | 1,035,771 | C++ - linking to 3rd party DLL - intermittent access violation | I have been provided with a C++ DLL and associated header file in order to integrate it with my application. To begin with, I am simply trying to call the DLL from a simple Win32 console application (I'm using Visual Studio 2008 Express).
I've linked the DLL by specifying it as an additional dependency in the project s... | It won't have anything to do with the DLL being unloaded; different processes using the same DLL do not share any state. Also, the DLL will be unloaded when the process exits; perhaps not gracefully, but it will be unloaded.
I can think of two likely reasons for an intermittent failure.
Most likely, the DLL has a ra... |
1,036,001 | 1,036,014 | C/C++ Memory Problem? | Programming for my Arduino (in some kind of mix of C/C++), I noticed something weird.
Everytime I communicate through the serial port, I keep an eye on the SRAM usage. Normally, it ranges between 300~400 bytes.
However, after adding a new routine (see below), I noticed it always jumped from 300~400 bytes of free memory... | The reason you're getting 1023 bytes of free memory is purely because the malloc (on 1023 - which is --1024) is succeeding on the first try. This means you have at least 1023 bytes of memory - but doesn't tell you the true available memory.
Prior to this, you must have had something keeping memory around. My guess is... |
1,036,019 | 1,036,099 | Does calling a destructor explicitly destroy an object completely? | If I call a destructor explicitly ( myObject.~Object() ) does this assure me that the object will be appropriately destroyed (calling all child destructors) ?
Ok some code:
class Object
{
virtual ~Object()
{}
};
class Widget : public Object
{
virtual ~Widget()
{}
};
...
Object* aWidget = new Widget(); //... | The answer is... nearly always.
If your object has a non-virtual destructor, and is then sub-classed to add child elements that need freeing... then calling the destructor on the object base class will not free the child elements. This is why you should always declare destructors virtual.
We had an interesting case wh... |
1,036,625 | 1,036,706 | Differentiate between a unix directory and file in C and C++ | Given a path, say, /home/shree/path/def, I would want to determine if def is a directory or a file. Is there a way of achieving this in C or C++ code?
| The following code uses the stat() function and the S_ISDIR ('is a directory') and S_ISREG ('is a regular file') macros to get information on the file. The rest is just error checking and enough to make a complete compilable program.
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
int main (int argc, char ... |
1,036,924 | 1,037,259 | generate fusion::vector from mpl::vector | How to generate fusion::vector from mpl::vector?
How to generate mpl::vector from fusion::vector?
BOOST_MPL_ASSERT((is_same<
fusion::vector<int, char>,
generate_fusion_vector<mpl::vector<int, char> >::type >));
BOOST_MPL_ASSERT((is_same<
mpl::vector<int, char>,
... | As fusion accepts mpl types as arguments to functions you could try this:
BOOST_MPL_ASSERT((is_same<
fusion::vector<int, char>,
fusion::result_of::as_vector<mpl::vector<int, char> >::type >));
Edit:
I think the reason this isn't working for you is that you have to include certain header files to enable mpl compatibil... |
1,036,976 | 1,036,980 | good combination of a c++ toolkit/library, cross platform db (not necessarily sql) | what do you suggest as a cross platform "almost all encompassing" abstraction toolkit/library, not necessarily gui oriented?
the project should at some point include an extremely minimal web server and a "db" of some sort (basically to have indexes/btrees, maybe relations, so a rdbms is desiderable but avoidable if nec... | For a minimal webserver, I think you're fine using Boost.Asio and sqlite -- it's quite portable, and should have everything you need. Remember that the C/C++ runtimes also provide portable abstractions for many things, so be sure to check those first (especially if a minimum overhead is required -- it might be simply e... |
1,037,043 | 1,037,221 | how to avoid "already defined error" in C++ | I am gettings these type of errors in a MFC VS6 project while linking the application:
msvcrt.lib(MSVCRT.dll) : error LNK2005: _atoi already defined in LIBC.lib(atox.obj)
I know what it means (a function exists in 2 different libraries); to solve it I should have to exclude one of the 2 libraries (msvcrt.lib or libc.l... | There seems to be an option which you can use to ignore errors like this: in projectsettings > link > check 'Force file output'. This will generate the program even if there are linkerrors.
The Build output gives something like this:
msvcrt.lib(MSVCRT.dll) : warning LNK4006: _atoi already defined in LIBC.lib(atox.obj);... |
1,037,532 | 1,037,564 | COM automation using tlb file | Consider me a novice to windows environment and COM programming.
I have to automate an application (CANoe) access. CANoe exposes itself as a COM server and provides CANoe.h , CANoe_i.c and CANoe.tlb files.
Can anyone specify how to write a C++ client, for accessing the object, functions of the application.
Also, pleas... | Visual studio has a lot of built in support for importing type libraries into your C++ project and using the objects thus defined. For example, you can use the #import directive:
#import "CANoe.tlb"
This will import the type library, and convert it to header files and implementation files - also it will cause the impl... |
1,037,575 | 1,037,665 | Why aren't exceptions in C++ checked by the compiler? | C++ provides a syntax for checked exceptions, for example:
void G() throw(Exception);
void f() throw();
However, the Visual C++ compiler doesn't check them; the throw flag is simply ignored. In my opinion, this renders the exception feature unusable. So my question is: is there a way to make the compiler check whether... | Exception specifications are pretty useless in C++.
It's not enforced that no other exceptions will be thrown, but merely that the global function unexpected() will be called (which can be set)
Using exception specifications mainly boils down to deluding yourself (or your peers) into some false sense of security. Bette... |
1,037,662 | 1,681,240 | How to make MSVC debug builds run faster | We have a large C++ application, which sometimes we need to run as a debug build in order to investigate bugs. The debug build is much much slower than the release build, to the point of being almost unusable.
What tricks are available for making MSVC Debug builds execute faster without sacrificing too much on the deb... | Use #pragma optimize("", off) at the top of selected files that you want to debug in release. This gives better stack trace/variable view.
Works well if it's only a few files you need to chase the bug in.
|
1,038,070 | 1,044,498 | Retrieving DLL name, not calling application name | I've written two COM classes in C++, contained in a single MFC DLL. They're being loaded as plugins by a 3rd party application.
How can I get the file name, and version number, of the DLL from within those classes?
| CString GetCallingFilename(bool includePath)
{
CString filename;
GetModuleFileName(AfxGetInstanceHandle(), filename.GetBuffer(MAX_PATH), MAX_PATH);
filename.ReleaseBuffer();
if( !includePath )
{
int filenameStart = filename.ReverseFind('\\') + 1;
if( filenameStart > 0 )
{
... |
1,038,302 | 1,038,485 | How to make data ownership explicit in C++ | When working with pointers and references in C++, it is sometimes difficult to see whether the pointer has ownership over the referenced data, or if it is just a temporal reference. For example:
Instance* i = new Instance();
Instance* j = i;
How can it be made clear which of the 2 pointers has ownership over the insta... | You cannot determine the owner, since there is no built in mechanism to know which pointer is owning the memory the pointer points to.
If you are really concerned about this, you could always introduce your own naming convention, e.g. through some pre/post-fix to your variable names. In other words, it's your code desi... |
1,038,482 | 1,038,504 | c++ exceptions, can what() be NULL? | Can a caught std::exception ever have what() being NULL?
Is the checking for e.what() below overhead?
//...
}
catch (const std::exception& e)
{
std::string error;
if(e.what())
error = e.what();
}
| The contents of the string is implementation defined, so I guess the answer is yes.
Edit: Belay that. The standard says:
virtual const char* what() const throw();
5 Returns: An implementation-defined NTBS.
So it must return a string, not just a pointer. And a string cannot be NULL. As others have pointed out it is eas... |
1,038,708 | 1,039,267 | Erase/Remove contents from the map (or any other STL container) while iterating it | Allegedly you cannot just erase/remove an element in a container while iterating as iterator becomes invalid. What are the (safe) ways to remove the elements that meet a certain condition? please only stl, no boost or tr1.
EDIT
Is there a more elegant way if I want to erase a number of elements that meet a certain crit... | bool IsOdd( int i )
{
return (i&1)!=0;
}
int a[] = {1,2,3,4,5};
vector<int> v( a, a + 5 );
v.erase( remove_if( v.begin(), v.end(), bind1st( equal_to<int>(), 4 ) ), v.end() );
// v contains {1,2,3,5}
v.erase( remove_if( v.begin(), v.end(), IsOdd ), v.end() );
// v contains {2}
|
1,039,627 | 1,040,094 | Why is the beginning of my string disappearing? | In the following C++ code, I realised that gcount() was returning a larger number than I wanted, because getline() consumes the final newline character but doesn't send it to the input stream.
What I still don't understand is the program's output, though. For input "Test\n", why do I get " est\n"? How come my mistake... | I've also duplicated this result, Windows Vista, Visual Studio 2005 SP2.
When I figure out what the heck is happening, I'll update this post.
edit: Okay, there we go. The problem (and the different results people are getting) are from the \r. What happens is you call input.getline and put the result in vecBuffer. The g... |
1,039,667 | 1,039,719 | Why does std::fstream set the EOF bit the way it does? | I recently ran into a problem caused by using fstream::eof(). I read the following line from here:
The function eof() returns true if the end of the associated input file has been reached, false otherwise.
and (mistakenly) assumed this meant that if I used fstream::read() and read past the end of the file, the funct... | Because this way it can detect EOF without knowing how large the file is. All it has to do is simply attempt to read and if the read is short (but not an error), then you have reached the end of the file.
This mirrors the functionality of the read system call, which file IO typically ends up calling (win32 stuff may ca... |
1,039,671 | 1,039,710 | Disabling Vista-Style controls in Application | So I'm trying to recompile an application to add some minor features. All is well, except for one thing.
The old version has all the windows-vista-style dialog buttons. The corners are rounded, the radio buttons look different, etc.
Example
How do I turn those things on? I want it to look/feel like the original. ... | It seems that your version has classic window style (not Vista). To use Vista style as in "THEIR VERSION" check that somewhere in headers there is the following code:
#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0'... |
1,039,779 | 1,039,794 | ISAPI Extensions: What is the difference between TerminateExtension and the extensions destructor? | Is there a difference between TerminateExtension() and the extensions destructor? Obviously both are used to cleanup resources but what kind of cleanup should be in one function and not the other?
| The TerminateExtension function takes a DWORD dwFlags. If this is HSE_TERM_ADVISORY_UNLOAD, you can return FALSE or TRUE to either allow or block the unloading from happening.
There's no such option in your class's destructor of course.
http://msdn.microsoft.com/en-us/library/ms524470.aspx
|
1,039,805 | 1,040,096 | Building .NET COMInterop project without first registering the COM service | I am building a C# UI to interact with a COM Service (.exe). The VS2005 COM project outputs a valid typelib (TLB), which is referenced by the C# project. However, the VS2005 C# project insists that the service be registered in order to build the C# project, even though the typelib appears perfectly valid when examine... | Solved this by adding a -regtypelib command to the COM service, which calls the AtlRegisterTypeLib function but does not register the service. Suboptimal because it will leave registery entries on the build server, but quick and it works.
|
1,039,853 | 1,039,904 | Why is the STL so heavily based on templates instead of inheritance? | I mean, aside from its name the Standard Template Library (which evolved into the C++ standard library).
C++ initially introduce OOP concepts into C. That is: you could tell what a specific entity could and couldn't do (regardless of how it does it) based on its class and class hierarchy. Some compositions of abilities... | The short answer is "because C++ has moved on". Yes, back in the late 70's, Stroustrup intended to create an upgraded C with OOP capabilities, but that is a long time ago. By the time the language was standardized in 1998, it was no longer an OOP language. It was a multi-paradigm language. It certainly had some support... |
1,039,918 | 1,040,740 | Boost Thread Cancelling | Can you cancel a Boost Thread as you would a pthread?
I'm writing a simple watchdog to terminate worker threads if they crash and there doesn't seem to be a way to simply cancel a thread in the Boost Thread library.
| They don't support cancel, which is a good thing since it can cause all manner of subtle problems.
Take a look at the section of docs that cover thread interruption and the boost::thread_interrupted exception and fashion something that allows you to accomplish what you want while also cleaning things up.
|
1,040,319 | 1,040,595 | Boost asio ip tcp iostream Error Detection | Greetings. I'm just getting started with the boost::asio library and have run into some early difficulty related to boost::asio::ip::tcp::iostream.
My question has two parts:
1.) How does one connect an iostream using simply host and port number?
I can make the client and server [boost.org] examples work fine as code... | I don't know why asio doesn't work (at least with Boost 1.35.0) with a port number expressed as an int. But, you can specify the port number as a string. i.e.
tcp::iostream s(hostname, "13");
should work.
concerning error detection:
tcp::socket has a connect() method which takes and endpoint and a reference to a boost... |
1,040,384 | 1,040,556 | Why do some languages need Boxing and Unboxing? | This is not a question of what is boxing and unboxing,
it is rather why do languages like Java and C# need that ?
I am greatly familiar wtih C++, STL and Boost.
In C++ I could write something like this very easily,
std::vector<double> dummy;
I have some experience with Java, but I was really surprised because I had to... |
what is so hard technically to include primitive types when talking about Generics ?
In Java's case, it's because of the way generics work. In Java, generics are a compile-time trick, that prevents you from putting an Image object into an ArrayList<String>. However, Java's generics are implemented with type erasure: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.