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* to an std::fstream object? Or, if not is tmpfile() functionality available in the standard, or another library?
Thanks!
My OS is Windows XP and I use either Dev-C++ 4.9.9.2 or MS Visual Studio 2008 as my compiler.
|
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);
std::fstream file(name);
You do have to delete the file yourself, though, using remove() or some other method.
|
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 triplet for which a + b + c = 1000.
Find the product abc.
My solution is in c++:
int a,b,c;
const int sum = 1000;
int result = -1;
for (a = 1; a<sum; a++){
for (b = 1; b < sum; b++){
c = sum-a-b;
if (a*a+b*b == c*c){
result = a*b*c;
goto found;
}
}
}
found:
std::cout << "a:" << a << std::endl;
std::cout << "b:" << b << std::endl;
std::cout << "c:" << c << std::endl;
std::cout <<"Result:" << result << std::endl;
Since "goto" statements are not very popular among c++ programmers, i would like to know, if this could be considered a reasonable use of "goto". Or if there is a better solution for the problem that doesn't need "goto". By that I don't mean a solution which just avoids "goto", but which avoids "goto" in a way that improves the algorithm.
|
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;
return a*b*c;
}
}
return -1;
}
int main() {
int a, b, c;
const int sum = 1000;
int result = findit(sum, &a, &b, &c);
if (result == -1) {
std::cout << "No result!" << std::endl;
return 1;
}
std::cout << "a:" << a << std::endl;
std::cout << "b:" << b << std::endl;
std::cout << "c:" << c << std::endl;
std::cout <<"Result:" << result << std::endl;
return 0;
}
|
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++):
env LIBS=-lprofiler ./configure
make
make install
I then run profile the installed application (jags) with:
env CPUPROFILE=./jags.prof /usr/local/bin/jags regression.cmd
pprof /usr/local/bin/jags jags.prof
Unfortunately, I get the error:
pprof /usr/local/bin/jags jags.prof Can't exec "objdump":
No such file or directory at /usr/local/bin/pprof line 2833.
objdump /System/Library/Frameworks/Accelerate.framework/Versions/A/
Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib: No such file or directory
The program dynamically links to libLAPACK.dylib. So prof does not seem to understand it (?). I thought about trying to statically link, but the documents associated with the program say that it is impossible to statically link in LAPACK or BLAS (two required libraries).
Is there a way to have the profiler ignore libLAPACK? I'm okay if it doesn't sample within libLAPACK. Or how might I get profiling to work?
|
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: May be helpful to note that I'm actually trying to retrieve the name of a derived class, and I'm using Visual C++ 2008 Express Edition.
|
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 libc++), you can demangle names using the __cxa_demangle function (on MSVC demangling does not seem necessary):
#include <cxxabi.h>
#include <cstdlib>
#include <memory>
#include <string>
std::string demangle(char const* mangled) {
auto ptr = std::unique_ptr<char, decltype(& std::free)>{
abi::__cxa_demangle(mangled, nullptr, nullptr, nullptr),
std::free
};
return {ptr.get()};
}
This will still not necessarily be a readable name — for instance, std::string is a type name for the actual type, and its complete type name in the current libstdc++ is std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >; by contrast, in the current libc++ it’s std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >. “Prettifying” type aliases is unfortunately not trivial.
|
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 having to run through all of the code and finding the bug that is causing it?
Thanks in advance.
|
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 finding your bug, then tell us more. Otherwise, build your release with debug symbols (pdbs), install DrWatson as the system debugger and run it standalone. When it crashes DrWatson will create a minidump file, load this into WinDbg (my favourite) and you'll be able to see exactly where your bug is (it'll even tell you that the dump contains an exception and show you it by default. You need to add your source code path and path to your symbols in WinDbg to get it to do this correctly).
Then you will also know how to diagnose crashes when the app is run on-site too.
|
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) - offsetof(myStruct, c));
I am asking if there is any recommended/elegant way?)
|
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 defined on them, instead of allowing the whole program to have knowledge of the internal layout of data structures.
That said, the offsetof technique you describe will work on plain old data objects, because they are no different to C structs.
|
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 {
public:
explicit ArrayOwner( int* initialArray ) : _ptrToArray(initialArray) {}
virtual ~ArrayOwner() { delete [] _ptrToArray; }
private:
int* _ptrToArray;
}
This usage will be ok: ArrayOwner
foo( new int[10] );
But this usage
leads to undefined behaviour:
ArrayOwner foo( new int() );
I would like to add assert in the constructor, that the "initialArray" pointer is really an array pointer. I cannot change the contract of the constructor, use vectors e.t.c. Is there any way to write this assert in C++?
|
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;
//Construction and Destruction
curvePoint(): point(NULL), dimensions(0) {}
virtual ~curvePoint(){if(point!=NULL) delete[] point;}
//Mutators
void convertToIndex(){ if(isTuple()) calc(this); }
void convertToTuple(){ if(isIndex()) calc(this); }
void setTuple(quint16 *tuple, int size);
void setIndex(quint16 *index, int size);
void setAlgorithm(curveType alg){algorithm = alg;}
//Inspectors
bool isIndex(){return current==Index;}
bool isTuple(){return current==Tuple;}
size_t size(){return dimensions;}
quint16 operator[](size_t index);
enum curveType{HilbertCurve, ZCurve, GrayCodeCurve};
enum status{Index, Tuple};
private:
curveCalculate calc;
curveType algorithm;
quint16 *point;
size_t dimensions;
status current;
};
(The length of the array pointed to by point is dimensions)
Anyways in the implementation of operator[] I was wondering what the best method to achieve bounds checking is. I want to avoid throwing exceptions if at all possible, and the full range of values is usable for each number in the array so a special value to return in case of an out of bounds error is not possible either;
I was thinking of something like this though implemented in the class definition:
quint16 curvePoint::operator[](size_t index)
{
return point[ index % dimensions ];
}
This makes it so that we never leave the bounds of the array and if well documented I think it would be fine; nevertheless, I am leary of this particular implementation.
Does this look acceptable to others?
Is there any other way of doing bounds checking while still satisfying my constraints?
Edit:
Calculation of things like Hilbert curves etc are highly messy, messy enough that I do not not want the additional interface for the stl libraries in the way.
Additionally because I will have to convert many thousands of these every time the multidimensional database is queried I do not want the additional cost of the stl function calls in the mix, if at all possible.
I rather like the idea of the assert; but, if I remember correctly that breaks in release builds does it not?
I suppose I can use exceptions, that seems to be what everyone is rooting for, but I am using the Qt libraries and those avoid exceptions for both performance and portability and I was hoping to do the same.
|
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 and use std::vector::at
Hence, if you do the same for your class, you can document the out-of-bound behavior as "standard".
|
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 applies within the current header file, but to everything that is compiled thereafter. This partly nullifies the advantage of namespaces. Consider for example a header file in which the classes "ourlib::networking::IpAddress" and "ourlib::filesystem::Path" are frequently used.
Is there a way to limit the effect of the "using namespace"-declaration in header files?
|
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(5))
int digit3 = atoi(&bigNumber.at(12));
std::cout << "digit: " << digit << std::endl;
std::cout << "digit2: " << digit2 << std::endl;
std::cout << "digit3: " << digit3 << std::endl;
}
This will produce the following output.
digit: 7
digit2: 2147483647
digit3: 57230
The first one is the desired result. The second one seems to me to be a random number, which I cannot find in the string. The third one is the end of the string, but not just a single digit as I expected, but up from the 12th index to the end of the string. Can somebody explain the different outputs to me?
EDIT: Would this be an acceptable solution?
char tmp[2] = {bigNumber.at(5), '\0'};
int digit = atoi(tmp);
std::cout << "digit: " << digit << std::endl;
|
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 variable - the behaviour of this call is undefined since the memory immediately following the character in memory is unknown. To be exact, you would have to create a null terminated string and pass that in.*
char tmp = bigNumber.at(5);
int digit = atoi(&tmp);
This line gets a pointer to the character in position 5 in the string. This happens to be a pointer into the original big number string above - so the string parameter to atoi looks like the string "5720394857230". atoi will clearly oveflow trying to turn this into an integer since no 32 bit integer will hold this.
int digit2 = atoi(&bigNumber.at(5))
This line gets a pointer into the string at position 12. The parameter to atoi is the string
"57230". This is converted into the integer 57230 correctly.
int digit3 = atoi(&bigNumber.at(12));
...
}
Since you are using C++, there are nicer methods to convert strings of characters into integers. One that I am partial to is the Boost lexical_cast library. You would use it like this:
char tmp = bigNumber.at(5);
// convert the character to a string then to an integer
int digit = boost::lexical_cast<int>(std::string(tmp));
// this copies the whole target string at position 5 and then attempts conversion
// if the conversion fails, then a bad_lexical_cast is thrown
int digit2=boost::lexical_cast<int>(std::string(bigNumber.at(5)));
* Strictly, atoi will scan through the numeric characters until a non-numeric one is found. It is clearly undefined when it would find one and what it will do when reading over invalid memory locations.
|
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 are now submatrices of W.
How can I make b a LaVectorDouble to be able to perform some calculations with it?
|
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):
int *ptrHeapArray = new int[10];
for(int f=9; f>=0 ;f--)
{
*ptrHeapArray = f;
ptrHeapArray++;
}
for(int f=0; f<10; f++)
cout << ptrHeapArray[f] << "\n";
It prints out compleletly unexpected values.
As I understand the above, the 'new' command creates an array on the heap and sends me back a pointer to the address where the array is. Since the pointer I assign (ptrHeapArray) is of int size I assumed I could use pointer post incrementing to navigate through the array. However the results indicate that my assumptions are wrong.
This got me to thinking that perhaps the pointer passed back by the 'new' keyword is just a pointer to the whole array and can't be used to step through the array for some reason.
So I tried creating another pointer to the pointer returned by the 'new' keyword and used that to do my array population:
int *ptrHeapArray = new int[10]; //array to hold FRANK data in 32 bit chunks
int *ptrToHeapArrayPointer = ptrHeapArray;
for(int f=9; f>=0 ;f--)
{
*ptrToHeapArrayPointer = f;
ptrToHeapArrayPointer++;
}
for(int f=0; f<10; f++)
cout << ptrHeapArray[f] << "\n";
This worked fine.
Can anyone explain to me why I had to do this and couldn't just have used the pointer passed backed to me by the 'new' keyword?
Thanks
|
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. When ptrHeapArray points to the third of the integers:
[0] [1] [2] [3] [4]
^ ^ ^
orig. | |
| +-- ptrHeapArray[2]
|
+-- ptrHeapArray now points here
then ptrHeapArray[2] would give you the integer at the position orignally numbered with 4.
|
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 n1:" <<n1<<"\n";
}
};
class B : public I
{
public:
void fun(int n, int n1)
{
std::cout<<"B::fun():" <<n<<" and n1:" <<n1<<"\n";
}
};
int main()
{
std::vector<I*> a;
a.push_back(new A);
a.push_back(new B);
//I want to use std::for_each to call function fun with two arguments.
}
How do I call fun() method which takes two arguments using the std::for_each ? I think I have to use std::mem_fun probably with std::bind2nd but am not able to figure out how to do this. Any clue how to achieve this? I am not using boost.
|
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::bind like this:
std::for_each(
a.begin(),
a.end(),
boost::bind(&I::fun, _1, n, n1));
|
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).
However, I'm wondering if there's anything out there which will translate the SVG directly to a sequence of OpenGL calls and render it using OpenGL's lines, polygons and the like. Anyone know of anything which can do this ?
|
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 prevent hard-to-find bugs I feel obliged to cater for different usages, for example:
char* name = (char*) malloc(14);
strcpy(name, "my test suite");
TestSuite suite(name);
free(name);
// ...
suite.run(); // Suite name is used here
As such I have implemented TestSuite like this:
class TestSuite {
public:
TestSuite(const char* name) {
name_ = (char*) malloc(strlen(name) + 1);
strcpy(name_, name);
}
~TestSuite() {
free(name_);
}
private:
char* name_;
};
Putting aside the issue of failing to deal with memory allocation failures in the constructor I'd prefer to simply allocate the pointer to a member variable like this:
class TestSuite {
public:
TestSuite(const char* name) : name_(name) {
}
private:
const char* name_;
};
Is there any way I can change the interface to force it to be used 'correctly' so that I can do away with the dynamic memory allocation?
|
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 that it is still possible to subvert this mechanism by passing a const char* to the constructor when the name is in fact dynamically allocated. However, this may be sufficient for your purposes.
I should note that I have never actually seen this technique used in an API, it was just a thought that occurred to me as I was reading your question.
|
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 projects takes a very long time! Much longer than in VS6.
Some classes have a lot of codelines, a few thousands even. These are just arrays to be filled in the code with a lot of items. I know it's not the perfect solution but this is how it is at the moment and VS6 never had a problem with that.
Maybe there are just some settings I have to adjust to speed things up but if it stays like it is now I will keep it as an VS6 project since I don't want to sit at my desk all day doing nothing.
Any ideas?
|
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();
~ReportData()
{
ReportFileData.clear();
ReportSupressionData.clear();
}
};
I can add this lib file to my project and create instances of this class no problem.
My question is, how can i move this to a DLL and dynamically load it, and create instances of this class. What i'm wanting to do is move some common functionality into this dll and share it across multiple projects.
I want to be able to re-compile the dll if needed when changes are made and have the projects use the must recent version; as of now, using a lib, I have to recompile every project after I recompile the dll for the changes to take place, and because the way this system was originally designed, there are 100+ projects that will use this lib/dll and I don't want to recompile 100 different projects each time a change is made.
So, please give me your expert opinions on how i should go about doing this.
I'll be using the dll inside of my projects like so:
ReportData *rd = new ReportData();
ReportData::ClientName = "test";
rd->ReportFileData.push_back(new FileData("testing", 10, 1));
rd->ReportFileData.push_back(new FileData("testing 2", 20, 1));
std::cout << rd->GenFileConfTemplate();
delete rd;
I ended up with something like this:
typedef Foo* (__stdcall *CreateFunc)();
int main()
{
HMODULE dll (LoadLibrary ("..\\LLFileConfirmDLL\\LLFileConfirmDLL.dll"));
if (!dll) {
cerr << "LoadLibrary: Failed!" << endl;
std::cin.get();
return 1;
}
CreateFunc create (reinterpret_cast<CreateFunc>(GetProcAddress (dll, "create")));
if (!create) {
cerr << "GetProcAddress: Failed!" << endl;
std::cin.get();
return 1;
}
Foo *f = create();
cerr << f->Test();
FreeLibrary (dll);
std::cin.get();
return 0;
}
struct FOOAPI Foo
{
Foo();
virtual ~Foo();
virtual int Test();
};
Foo::Foo()
{
}
Foo::~Foo()
{
}
int Foo::Test()
{
return 5;
}
extern "C" __declspec(dllexport) Foo* __stdcall create()
{
return new Foo;
}
|
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:
extern "C"
BOOL CreateObject(REFCLSID rclsid, void** ppv) {
BOOL success = false;
*ppv = NULL;
if (rclsid == CLSID_ReportData) {
ReportData* report_data = new ReportData();
if (report_data) {
*ppv = report_data;
success = true;
}
} else if (...) {
... other objects ...
}
return success;
}
Of course, now you have to worry about things like who will free the object, making sure the DLL doesn't get unloaded, etc.
See also DllGetClassObject, DllCanUnloadNow, etc.
|
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+PUBLISH_TIMEOUT)>local_time)
{
fireEvent();
local_time=current_time;
}
}
|
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() {
static struct timeval msec_base;
struct timeval now;
long seconds, useconds;
if (!msec_base.tv_usec)
gettimeofday(&msec_base, NULL);
gettimeofday(&now, NULL);
seconds = now.tv_sec - msec_base.tv_sec;
useconds = now.tv_usec - msec_base.tv_usec;
return ((seconds) * 1000 + useconds/1000.0);
}
|
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 method preferable to the other?
Thanks a lot!
|
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 pointers, for instance.
I hate how they clutter the code but given all the advantages, I'd prefer them over function pointers any time.
|
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 foo() { return 42; }
};
How is the function overridden in the three different base classes? Are my three following assumptions correct? Are there any other caveats?
With BaseA, the child class doesn't compile, the pure virtual function isn't defined.
With BaseB, the function in the child is called when calling foo on a BaseB* or Child*.
With BaseC, the function in the child is called when calling foo on Child* but not on BaseB* (the function in parent class is called).
|
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 intended, with foo() being virtual() and executing in class Child.
With BaseC however, it will compile and execute, but it will execute the BaseC version if you call it from the context of BaseC, and the Child version if you call with the context of Child.
|
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/singleton classes for scoping). Yes, it's not 'real' OO, I've been planning to do the C# conversion first to avoid creating any conversion issues while converting.
It makes very limited use of the STL (The queue class) in the pathfinding module, and because it's a game, it also doesn't do any memory allocation outside of the third party sound library in a DLL, and what's necessary for loading the graphics bitmaps.
I want to convert it into idiomatic C#. I'd rather not hold a discussion on whether this is a good idea, I understand that it isn't, let's please let part go. Assume that I've got overriding reasons please.
I've also done my research, and there is a thread that is somewhat relevant about converting the methods using reflector. I plan to look more deeply into it when I get a chance.
Translate C++/CLI to C#
There is also one pay applicaiton that will convert from C++ to C# that I may look at if that doesn't work as well as I'd like.
The hardest part is going to be rewriting the interface in either WPF/Silverlight or XNA (or both) There are pros and cons to each one, but I'm leaning towards WPF right now because of the font support, and because that way I won't have to write all the widgets. I may end up doing both, an XNA quick port, and a WPF one later.
There are several possible approaches to this, and I wanted to know if anyone had any experience with a conversion like this, and any suggestions or pitfalls.
1) Create the UI first, This involves either leaving the Graphics module as is, and converting from GDI to raw GDI like calls in XNA, and converting later to WPF one dialog at a time.
2) Convert the guts first, and leave the main UI in C++/CLI for now, after the guts are converted, switch over the interface one dialog at a time to WPF.
A related question is whether it's worth doing this module by module, or basically all at once, and whether it's better to do a rough conversion into C# and clean everythig up, or clean up everything in C++ then convert to C#.
The thought right now is to rewrite the event loops to use a home grown common loop like MFC, then try to convert everything at once to C#. Leave the graphics in C++ and see what breaks. After that, move to XNA and provide a WPF layer later. The last two steps are arbitrary, I think that the XNA port is going to be simpler, but using WPF basic panel may be pretty simple too.
I'm open to any suggestions that may help.
Thanks,
Ralph
|
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 access to the parse tree (and understand parse trees), I may (and may not) customize it to change char * to String, etc. If I do much customization, I'll probably create an open source version, probably on CodePlex.
|
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 just a wrapped ostream with some logging-level functionality similar to log4j (debug, fatal, debug, etc).
I was wondering, what do others do to manage logging performance, specifically in message processing activities? How do you manage these I/O bound activities? Do you stripe it out? Do you move to databases instead?
Any advice for optimizing logging is appreciated.
Note: I recognize that there might be other problems with our system that causes the outliers, but for the sake of this question I am only interested in logging optimizations, thanks.
Also: Logging is mandatory for our system.
|
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 searching for the key in the index-file and going in the text-file to the address it shows.
The index-file should be built up as follows:
KEY ADDRESS
1 0xABCDEF
2 0xFEDCBA
. .
. .
We have a text-file with the following example value:
1, 8752 FW,
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,
******************************************************************************,
------------------------------------------------------------------------------;
I hope that this explains my question a bit better.
Thanks!
|
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 locations with the data written.
For example, your Key locations may be where each new data block written into the file starts from. e.g. first block 1000 bytes, key location 0; second block 2500 bytes, key location 1000; third block 550 bytes; key location 3500; the next block will be 4050 all assuming that 0 is the first byte.
Store the Key values in a variable length array and then you can easily retrieve the starting point for a data block.
If your Key point is signified by some key character then you can use the same class, but with a slight change to store where the Key value is stored. The simplest way is to step through the data until the key character is located, counting the number of characters checked as you go. The count is then used to produce your key location.
|
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 much more organized manner.
Still, I see these blocks around quite often. A common place to find them is near a message-loop (WndProc...), whereas these are among the places when they raise the heaviest havoc: variables are shared along the entire block, even when not propriate (and can't be initialized inside it). Extra attention has to be put on not dropping break's, and so on...
Personally, I avoid using them, and I wonder wether I'm missing something?
Are they more efficient than if/else's?
Are they carried on by tradition?
|
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 sparse - binary search or series of if/else, so in worst case switch is as fast as if/else, but typically faster. Although some compilers can similarly optimise if/else.
Test order doesn't matter. To speed up series of if/else tests one needs to put more likely cases first. With switch/case programmer doesn't need to think about this.
Default can be anywhere. With if/else default case must be at the very end - after last else. In switch - default can be anywhere, wherever programmer finds it more appropriate.
Common code. If you need to execute common code for several cases, you may omit break and the execution will "fall through" - something you cannot achieve with if/else. (There is a good practice to place a special comment /* FALLTHROUGH */ for such cases - lint recognises it and doesn't complain, without this comment it does complain as it is common error to forgot break).
Thanks to all commenters.
|
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.
Syntactically, it's legal (at least in VC++ 7), and it seems to run, but really I'd rather have him remove the & so there's no ambiguity as to what it's doing.
So, is this TRULY safe and legal and I'm obsessing? Does the temp object being constructed have a guaranteed lifetime? I had always assumed anonymous objects used in this manner were destructed after use...
So my question could also be generalized to anonymous object lifetime. Does the standard dictate the lifetime of an anonymous object? Would it have the same lifetime as any other object in that same scope? Or is it only given the lifetime of the expression?
Also, when doing it as a local, it's obviously scoped differently:
class A
{
string _str;
public:
A(const string& str) :
_str(str)
{
cout << "Constructing A(" << _str << ")" << endl;
}
~A()
{
cout << "Destructing A(" << _str << ")" << endl;
}
};
void TestFun()
{
A("Outer");
cout << "Hi" << endl;
}
Shows:
Constructing A(Outer);
Destructing A(Outer);
Hi
|
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 program
(3.6.2, 3.6.3)."
-- 2008 Working Draft, Standard for Programming Language C++, § 3.7.1 p. 63
As Martin noted, this is not the whole answer. The standard draft further notes (§ 12.2, p. 250-1):
"Temporaries of class type are created
in various contexts: binding an rvalue
to a reference (8.5.3) [...] Even when
the creation of the temporary object
is avoided (12.8), all the semantic
restrictions shall be respected as if
the temporary object had been created.
[...] Temporary objects are destroyed
as the last step in evaluating the
full-expression (1.9) that (lexically)
contains the point where they were
created. [...] There are two contexts
in which temporaries are destroyed at
a different point than the end of the
full-expression. [...] The second
context is when a reference is bound
to a temporary. The temporary to which
the reference is bound or the
temporary that is the complete object
of a subobject to which the reference
is bound persists for the lifetime of
the reference except as specified
below."
I tested in g++ if that makes you feel any better. ;)
|
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 won't compile as the auto_ptr cannot be copied without modifying the auto_ptr being copied. Ok, this means auto_ptr does not compose well like other types (in one more way). What is a good way of returning a new object in this case?
One alternative is to return a shared_ptr and another is an inout reference. But I am looking for some other alternative. I can do something like:
class AGetter
{
void getAExecute()
{
//...
// set a_ and i_
}
std::auto_ptr<A> getA() const
{
return a_.release();
}
int getInt() const
{
return i_;
}
private:
std::auto_ptr<A> a_;
int i_;
};
Is there a better way?
|
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;
typedef CGAL::Triangulation_2<K> Triangulation;
typedef Triangulation::Point Point;
The display is as follow:
delaunay_c::Triangulation::Edge_iterator eit = T.edges_begin();
delaunay_c::Triangulation::Edge_iterator end = T.edges_end();
for(;eit != end; ++eit)
{
delaunay_c::Triangulation::Segment s = T.segment(eit);
line.m_a = delaunay_c::convert(s.source());
line.m_b = delaunay_c::convert(s.target());
line.draw();
}
The function convert simply convert from CGAL Point to another point format
EDIT: following the chosen answer, I just change triangulation to delaunay_triangulation:
typedef CGAL::Delaunay_triangulation_2<K> Triangulation;
And it gave:
|
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 this; is it possible?
Given something like this
template<typename T>
class PointerWrapper
{
public:
PointerWrapper( T const * _pointer ): m_pointer(_pointer) {}
typedef T Type;
T const * m_pointer;
};
template<typename T>
class SomeObject: public NoCopyOrAssign
{
public:
SomeObject( void * _allocaBuffer, PointerWrapper<T> _source, int _count );
};
I want to do something like this:
void Test( PointerWrapper<int> _array, int _count )
{
SomeObject<int> object = MakeSomeObject( _array, _count );
// do some work with object
};
Code invoking the following macro doesn't compile, because the compiler cannot deduce SomeObject's template parameter from _wrappedPtr so complains that the template parameter is missing:
#define MakeSomeObject(_wrappedPtr, _runtimeCount) \
SomeObject(alloca(sizeof(_wrappedPtr::Type)*_runtimeCount), \
_wrappedPtr, _runtimeCount)
If a function templated on the pointer wrapper type is used, although the compiler can deduce the types implicitly, code invoking it doesn't compile because SomeObject deliberately defines but does not implement a copy constructor or assignment operator; even if it did compile it would not do the right thing because the memory provided by alloca() would immediately go out of scope:
template<typename WrappedT>
SomeObject<typename WrappedT::Type> MakeSomeObject
( WrappedT _pointer, uint _runtimeCount )
{
return SomeObject<typename WrappedT::Type>
( alloca(sizeof(typename WrappedT::Type)*_runtimeCount),
_pointer, _runtimeCount );
}
I'd like to avoid passing the type into the macro as an argument since in the real code this would result in quite lengthy, hard-to-read statements at the point of use, however I guess that is a fallback if nothing better is possible.
|
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<typename WrappedT>
int SizeT( WrappedT const _dummy ) { return sizeof(typename WrappedT::Type); }
#define MakeSomeObject(_wrappedPtr, _runtimeCount) \
_MakeSomeObject( alloca(SizeT(_wrappedPtr)*_runtimeCount), \
_wrappedPtr, _runtimeCount )
|
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();
virtual void getMapSection(float x, float y, int w, int h, bitset<MAX_SPRITE_PIXELS>* section);
};
I'm getting these compiler errors for the declaration of Entity::getBitMask():
error C2143: syntax error : missing ';' before '<'
error C2433: 'Entity::bitset' : 'virtual' not permitted on data declarations
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2238: unexpected token(s) preceding ';'
There are more similar errors for the next line as well. It seems like bitset isn't getting included but it clearly is? I can't figure out what's going wrong. WinMain.h includes windows.h, and numDefs.h includes nothing.
Using MS Visual C++ 2008.
|
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, stil there is a fragmentation.
Memory management of additional heaps seems to be low-level. So they are not easy to use.
In addition, additional heap can probably be emulated using allocations from heap and managing allocated memory.
So what is the usage? Did you use it?
|
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 used in an embedded system (which wasn't using Windows, so it didn't use those exact API functions). The custom memory allocator had a feature to "mark" a specific state of the heap and then "rewind" to that point if a process was aborted.
|
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's bad. If I put it in all of my .cpp files, the compiler doesn't recognize the std namespace.
How should this be done?
|
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 stuff in from a namespace that it's more readable to put a using namespace at the top of the source file. While it's easy to do this due to being lazy, try not to succumb to this temptation. At least by having it inside the specific source files it's visible to someone maintaining the code.
The third instance is generally poor practice. It can lead to problems if you're dependent on more than one external source file both of which may define the same method. Also, for someone maintaining your code it obfuscates where certain declarations are coming from. This should be avoided.
Summary:
Prefer to use scoped instances (std::Something) unless the excessive use of these decreases the legibility and maintainability of your code.
|
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 gets corrupted (is no longer 0). There is nothing in the constructors of ClassA or ClassB that mess with global_var.
Replacing new ClassB(a) with ClassB b(a) seems to solve the problem, although this doesn't allow me to do what I want (create a boost::ptr_vector with the new ClassB(a) instances).
Any ideas on what might be going wrong?
Update:
I'm really doing something like:
global_var = 0;
int main() {
boost::ptr_vector<ClassB> myobjects;
for(i = 0; i < N; ++i) {
ClassA a;
myobjects.push_back(new ClassB(a)); // seems to be problem!
}
}
Both create problems. But why is this a problem? Should I be doing something else to put a bunch of objects into a queue? I'm using myobjects it as the basis of a Command Pattern.
Update
`classB' looks like:
class ClassB {
public:
ClassB() {}
ClassB(ClassA a) : a_(a) {}
private:
ClassA a_;
}
ClassA is just a simple list initialization as well (in real life).
Problem?
Update
I believe this may have something to do with the fact that global_var is actually a complex matrix type and there may be issues with the way it allocates memory.
|
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 when I run this server on my own machine, everything works fine regardless of where I place the "server" folder. But when I give it to a colleague to test, they continually get:
java.lang.UnsatisfiedLinkError no someDLLFile in java.library.path
I want to have the DLL files live in the same folder as the jar files and would prefer not having someone configure their PATH variable.
Why does System.loadLibrary() work on my own machine regardless of the folder's location, but not on another computer?
|
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 deployment strategy and platform).
|
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:
FormViewClass::FormViewClass()
{
...
// originally I want to call Initialize function here
Initialize();
...
}
However, since I want this function to be responsible for all the initialization of this class when being created, and it contains MFC objects initializations such as combobox, edit control, checkbox control, radio button control, etc., should I be instead calling the Initialize() function here as I thought:
void FormViewClass::OnInitialUpdate()
{
// Should I call Initialize function instead here?
Initialize();
}
Currently I have non-MFC memory and object initialization in the constructor (hence calling Iniitalize() helper function in the constructor) and MFC object iniitalization in the OnIniitalUpdate() handler function. It would be great to hear your thoughts about it so that I can refactor the code properly. Thanks in advance.
|
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 OnInitialUpdate, but I don't think it does.)
|
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 compiles and works, so what is the purpose of the (void)?
|
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 to store that pointer in a variable that you can use to eventually delete the object and deallocate the memory. In your example, since the pointer is being discarded, an explicit cast to (void) makes the intention of the programmer clear: "I know exactly what I am doing - please discard the value returned by new"
If you are interested in the technicalities (quoting from the C++ standard, clause 5):
Any expression can be explicitly converted to type cv void. The expression value is discarded. [ Note: however, if the value is in a temporary variable (12.2), the destructor for that variable is not executed until the usual time, and the value of the variable is preserved for the purpose of executing the destructor. —end note ]
The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the expression.
And if you are wondering how those objects are getting deleted (if indeed they are getting deleted), the answer is that the 'this' pointer within the constructor of QShortcut should have the same value as that returned by new, and that can be passed to a ShortcutManager. Note, the 'this' within the constructor is not the same as the 'this' pointer that is being passed to the constructor of QShortcut.
|
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 like this:
static VALUE
MyMethod(VALUE self, VALUE flazm, VALUE saszm)
{
return Qnil;
}
It looks like rdoc expects old style "C" definitions like this:
static VALUE
MyMethod(self, flazm, saszm)
VALUE self;
VALUE flazm;
VALUE saszm;
{
return Qnil;
}
Is there anyway I can make this work?
|
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 one or more ways to invoke your method, which will be used instead of the default method(p1, p2) stuff.
/*
* call-seq:
* my_method(flazm, saszm) -> nil
* my_method(bunny) { |fluffy_ears| ... } -> true or false
*
* Method description here.
*/
static VALUE
MyMethod(VALUE self, VALUE flazm, VALUE saszm)
{
return Qnil;
}
* It is clueless about some other things as well. Regex-based "parsing" is very naive.
|
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 what the best way to store this simple data would be. I was leaning towards XML but it seems like it might be too heavy.
Each rule would only need a very small set of data (i.e. type of rule, value, applicable mask, etc).
Does anyone know of a good resource that I could look at that would perform a similar functionality. I'd rather not dig too deep into XML on a problem that seems to barely need a subset of the functionality I see in most of the examples I bump into.
If I can find a concise example to examine I would be able to decide on whether or not to just go with a flat file.
Thanks in advance for your input!
|
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 easier to understand the underlying data, modify it and extend functionality.
(Also, boost::serialization has an XML archive, but it isn't what I'd call easily modifiable)
|
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 exception obviously (though these cases are exceedingly rare).
UPDATE: Based on the answers below, I need to add constraints that are specific to our setup, which is a game for Wii/360/PS3. Very specific engine for a very specific application.
We have a deep hierarchy of game object classes (a design I never agreed with, but it's the design we are shipping). Deep and wide, actually. I am going to redo this for the next game to use a Dungeon Siege-style component-based system but in our current codebase, deep hierarchies make the DispatchVirtual() -> onVirtual() pattern difficult to apply.
Destructors do not get called for our game objects because delete doesn't get called. Game objects go into an add-only (stack) allocator-based pool during a world load. At the end of a level I just set the stack pointer back to the low water mark to free everything at once. In advance, we iterate all objects and call OnUnload on them so they can free any external resources they use. You might call it "garbage collection: the nuclear option". So no destructors.
Even if we could use a destructor-based approach it would only solve the narrow problem of an OnUnload or OnFree, but not OnUpdate, OnWorldMessage, OnLoaded, etc.
Runtime solutions are interesting but I hate relying on testing to catch this. Optimal would be either a compile-time template trick or an external static analysis tool I can use.
|
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 *=i;
for (int i2 = (first-second)-1; i2>=1; --i2)
bottom_fac *= i2;
return (top_fac/bottom_fac);
}
int combination(int first, int second)
{
int bottom_fac;
for (int i = second-1; i>=1; --i)
bottom_fac *= i;
return permutation(first, second)/(bottom_fac);
}
int main()
{
cout << "Enter two numbers.\n";
int first = 0;
int second = 0;
cin >> first >> second;
cout << "Now choose permutation(p) or combination(c).\n";
string choice;
cin >> choice;
if (choice == "p")
cout << "Number of permutations: " << permutation(first,second) << endl;
else if (choice == "c")
cout << "Number of combinations: " << combination(first,second) << endl;
else
cout << "p or c stupid.\n";
keep_window_open("q");
}
When I try to run the program, and I choose p or c, I get a "permutations_combinations.exe has stopped working" message. I tried to catch an error, but nothing is coming up. Any ideas?
Thanks in advance.
|
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 explicitly initialize top_fac and bottom_fac to 1 at the beginning of the permutation() and combination() functions.
I'm guessing that bottom_fac is accidentally getting initialized to 0, and then you're dividing by 0 at the end of the function, which is causing the runtime failure you're seeing.
|
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 bring up a window.
I'm curious on what options I have available to me, as I'm sure that there are many ways to do this. I'm most familiar with with Java though I have some experience with C++. I'm willing to explore other languages if they have some definite perks to them, though it would be nice to work with what I know in a way.
Thank you
|
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 the system tray. The icons can respond to mouse clicks and use pop up menus as well. However, this new functionality is a part of AWT, so it doesn't do a very good job integrating with Swing components.
Here's an example of a little clock that shows up in the system tray which was made using the SystemTray and TrayIcon classes in Java 6:
(source: coobird.net)
|
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 app begins we have a login page
with a choice of four modules. This
is implemented as a maindisplay
class. Each of the four modules is a
separate class in itself. The concerned module here is of action class which is responsible of gathering and displaying data from various systems.
User authentication gets him/her
into the action screen. The
constructor of the action screen
class executes and apart from
mundane initialisation it starts the
individual systems threads which are
implemented as singleton.
Each system protocol is implemented as a singleton thread of the form:
class SensorProtocol:public QThread {
static SensorProtocol* s_instance;
SensorProtocol(){}
SensorProtocol(const SensorProtocol&);
operator=(const SensorProtocol&);
public:
static SensorProtocol* getInstance();
//miscellaneous system related data to be used for
// data acquisition and processing
};
In implementation file *.cpp:
SensorProtocol* SensorProtocol::s_instance=0;
SensorProtocol* SensorProtocol::getInstance()
{
//DOUBLE CHECKED LOCKING PATTERN I have used singletons
// without this overrated pattern also but just fyi
if(!s_instance)
{
mutex.lock();
if(!s_instance)
s_instance=new SensorProtocol();
mutex.unlock();
}
}
Structure of run function
while(!mStop)
{
mutex.lock()
while(!WaitCondition.wait(&mutex,5)
{
if(mStop)
return;
}
//code to read from port when data becomes available
// and process it and store in variables
mutex.unlock();
}
In the action screen class I have define an InputSignalHandler using sigaction and saio. This is a function pointer which is activated as soon as data arrives on any of the serial ports.
It is a global function (we cannot change it as it is specific to Linux) which is just used to compare the file descriptors of the serial port where data has arrived and the fd's of the sensor systems, if a match is found WaitCondition.wakeOne is invoked on that thread and it comes out the wait and reads and processes the data.
In the action screen class the individual threads are started as SensorProtocol::getInstance()->start().
Each system's protocol has a frame rate at which it sends data. Based on this fact, in actions screen we set up update timers to time out at refresh rate of protocols. When these timers time out the UpdateSensorProtocol() function of operation screen is called
connect(&timer, SIGNAL(timeout), this,SLOT(UpdateSensorProtocol()));
This grabs an instance of sensor singleton as
SensorProtocol* pSingleton=SensorProtocol::getInstance();
if(pSingleton->mUpdate)
{
//update data on action screen GUI
pSingleton->mUpdate=false; //NOTE : this variable is set to
// true in the singleton thread
// while one frame is processed completely
}
For all uses of singleton instance SensorProtocol::getInstance() is used. Given the above scenario, One of my protocols is hanging no matter what changes I do.
The hang occurs in the while displaying data using UpdateSensorProtocol() If I comment ShowSensorData() function in the UpdateSensorProtocol() it works fine. But otherwise it hangs and the GUI freezes. Any suggestions!
Also, Since the main thread grabs the running instance of singleton, is it really multithreading because we are essentially changing mUpdate in singleton itself albeit from action screen.
I am confused in this.
Also, Can somebody suggest an alternate design as to what I am doing now.
Thanks In Advance
|
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 your program will crash at the program exit.
if(!s_instance){
QMutexLocker lock(&mutex);
if(!s_instance)
s_instance=new SensorProtocol( QApplication::instance());
}
But this isn't going to solve your problem ...
Qt is event driven so try to exployed this very nice event-driven architecture and create a eventloop for each system thread. Then you can create "SystemProtocols" that live in another threads and you can create timers, send events between threads, ... without using low level synchronization objects.
Have a look at the blog entry from Bradley T. Hughes Treading without the headache
Code is not compiled but should give you a good idea where to start ...
class GuiComponent : public QWidget {
//...
signals:
void start(int); // button triggerd signal
void stop(); // button triggerd singal
public slots:
// don't forget to register DataPackage at the metacompiler
// qRegisterMetaType<DataPackage>();
void dataFromProtocol( DataPackage ){
// update the gui the the new data
}
};
class ProtocolSystem : public QObject {
//...
int timerId;
signals:
void dataReady(DataPackage);
public slots:
void stop() {
killTimer(timerId);
}
void start( int interval ) {
timerId = startTimer();
}
protected:
void timerEvent(QTimerEvent * event) {
//code to read from port when data becomes available
// and process it and store in dataPackage
emit dataReady(dataPackage);
}
};
int main( int argc, char ** argv ) {
QApplication app( argc, argv );
// construct the system and glue them together
ProtocolSystem protocolSystem;
GuiComponent gui;
gui.connect(&protocolSystem, SIGNAL(dataReady(DataPackage)), SLOT(dataFromProtocol(DataPackage)));
protocolSystem.connect(&gui, SIGNAL(start(int)), SLOT(start(int)));
protocolSystem.connect(&gui, SIGNAL(stop()), SLOT(stop()));
// move communication to its thread
QThread protocolThread;
protocolSystem.moveToThread(&protocolThread);
protocolThread.start();
// repeat this for other systems ...
// start the application
gui.show();
app.exec();
// stop eventloop to before closing the application
protocolThread.quit();
protocolThread.wait();
return 0;
}
Now you have total independent systems, gui and protocols don't now each other and don't even know that the program is multithreaded. You can unit test all systems independently in a single threaded environement and just glue them together in the real application and if you need to, divided them between different threads.
That is the program architecture that I would use for this problem. Mutlithreading without a single low level synchronization element. No race conditions, no locks, ...
|
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;
VecABCD::const_iterator it;
for(it=vec.begin();it!=vec.end();it++)
sumOfA += it->a;
return sumOfA;
}
Say I wanted to do the same thing with 'b'? Easy! I'd write....essentially the same function, but with only trivial changes. Same with 'c' and 'd'.
So, is there a more concise, less repetitive way of doing this? I'd like to do something like:
int sumOfA = SumOfMembers(myVec, a);
but I can't conceive of how I'd put such a function together. Ideally, it'd be a template, and I could use it with a vector of any kind of structure, not specifically bound to VecABCD. Anyone have any ideas?
|
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 (const ABCD&)>& member)
{
return accumulate(v.begin(), v.end(),
0,
bind(plus<int>(),
_1,
bind(member, _2)));
};
// ...
int sum_a = sum_over_vec(vec, bind(&ABCD::a, _1));
Another way to do it, rather than putting your logic in the functor, would be to put the logic in the iterator, using a boost::transform iterator:
tr1::function<int (const ABCD&)> member(bind(&ABCD::a, _1));
accumulate(make_transform_iterator(v.begin(), member),
make_transform_iterator(v.end(), member),
0);
EDITED TO ADD: C++11 lambda syntax
This becomes somewhat clearer with the C++11 lambdas (though unfortunately not shorter):
accumulate(v.begin(), v.end(), 0,
[](int sum, const ABCD& curr) { return sum + curr.a });
and
int sum_over_vec(const vector<ABCD>& v, const std::function<int (const ABCD&)>& member)
{
return accumulate(v.begin(), v.end(), 0,
[&](int sum, const ABCD& curr) { return sum + member(curr}); });
};
Usage:
// Use a conversion from member function ptr to std::function.
int sum_a = sum_over_vec(vec, &ABCD::a);
// Or using a custom lambda sum the squares.
int sum_a_squared = sum_over_vec(vec,
[](const ABCD& curr) { return curr.a * curr.a; });
|
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 reasonable values so it looks like something was profiled but I'm mystified about the lack of other data.
All my source files are compiled in a similar way:
g++ -pg -O2 -DNDEBUG -I./ -ansi -c -o ScenarioLoader.o ScenarioLoader.cpp
I then run 'ar' to bundle all the object files into a library.
Later, I link and run gprof as so:
g++ -pg -lm -o vrpalone vrpalone.o ../src/atomicprof.a lastbuild.o
./vrpalone
gprof gmon.out | less
Any ideas?
|
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 is used to create objects and the latter is used to allocate memory for objects. The new operator calls operator new for the type of object being created, then initialises the object's v-table and calls the object's constructors. Reading this FAQ it says that operator new is not defined in the standard libraries. This is easy to fix, just define one:
void *operator new (size_t size)
{
return some allocated memory big enough to hold size bytes
}
and you'll need to define a delete as well:
void operator delete (void *memory)
{
free the memory
}
The only thing to add is the memory management, the allocation and freeing of blocks of memory. This can be done trivially, being careful not to clobber any existing allocated memory (the code, static / global data, the stack). You should have two symbols defined - one for the start of free memory and one for the end of the free memory. You can dynamically allocate and free any chunk of memory in this region. You will need to manage this memory yourself.
|
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 anything - except the following?
call constructors for all base classes recursively
call constructors and initializers (if any) for all member variables
set vtable pointer accordingly.
What other actions are there?
|
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 this is that a partially constructed object (think exceptions thrown in constructor) has its vtable set up to the point the construction proceeded to.
The order of construction/initialization is as follows:
virtual base classes in declaration order
nonvirtual base classes in declaration order
class members in declaration order
class constructor itself
|
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? would it be more secure instead of binding it in Client app?
The deployment will be done via an installer, verifying the version on each run.
|
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();
virtual double calculate_likelihood(Vector &data);
private:
Vector m_mean;
Vector m_covariance;
};
class FullCov_Gaussian : public Gaussian {
public:
virtual Vector get_mean();
virtual Matrix get_covariance();
virtual double calculate_likelihood(Vector &data);
private:
Vector m_mean;
Matrix m_covariance;
};
As you see, the class Gaussian acts as an interface but doesn't have any implementation. This is all working fine.
Now I want to make an class "AdaptedGaussian" where the data vector provided to the calculated_likelihood will be changed before the likelihood is calculated.
Some requirements:
The AdaptedGaussian must be a child-class of Gaussian
AdaptedGaussian must be able to "wrap" or "be an instance of" every possible Gaussian class
AdaptedGaussian must be constructed from an already existing Gaussian Object
The idea I have now is:
class Adapted_Gaussian : public Gaussian {
private:
Gaussian* m_g;
public:
virtual Vector get_mean() { return m_g->get_mean(); }
virtual Matrix get_covariance() { return m_g->get_covariance(); }
virtual double calculate_likelihood(Vector &data)
{
//do something with data
return g->calculate_likelihood(Vector &data);
}
}
There are maybe some disadvantages:
For every method (and there are more than showed here) a dummy method must be written in the new class
If Gaussian is ever extended, and this class would be forgotten, nasty bugs can appear.
Am I doing this in the right way? Or are there better methods to implement this?
Is there maybe a good way to standard delegate every non-implemented method to the same named method of m_g?
|
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 single method. All classes that do not want to implement every single method can just inherit from this dummy class and selectively override methods that interests them.
If you extend your Gaussian class with few more methods, as long as you declare them as pure virtual method you will get a compiler error in your child class file anyway.
|
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 0x43000000 -- correct)
But this doesn't?
outVal = *((unsigned long*)&((float)inVal));
(results in outVal being 0x00000080 -- NOT CORRECT :( )
Before asking this question I googled around a bit and found this function in java that basically does what I want. If you're a bit confused about what I'm trying to do, this program might help explain it:
class hello
{
public static void main(String[] args)
{
int inside = Float.floatToIntBits(128.0f);
System.out.printf("0x%08X", inside);
}
}
|
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 is still ill-defined since the size and internal representation of the involved types isn't specified and may differ depending on platform and compiler. You're probably safe, though.
|
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 me (or I fail at Google...) as I can only seem to get results on the Boost Test unit testing library. Does anyone know of such a Boost test suite?
GCC have a little bit of info here (http://gcc.gnu.org/testing/testing-boost.html), but they mention that their regression suite takes around 5 minutes to run on a Pentium 3 - which doesn't suggest to me that it's particularly comprehensive.
|
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.
Am i doing something wrong or is this a glitch with wxWidgets?
Windows 7 visual studio 2005 c++
Edit:
This is my current thread callback:
EVENT_CALLBACK_PTR_CPP(onProgress, UploadProgPage)
{
updateInfo* temp = static_cast<updateInfo*>(ptr);
if (temp)
{
wxOnUploadUpdateEvent event(wxEVT_UPLOAD_UPDATE, GetId(), temp, UPDATE_PROGRESS);
event.SetEventObject(this);
GetEventHandler()->AddPendingEvent(event);
}
}
And the progress update:
void UploadProgPage::onUpdate(wxOnUploadUpdateEvent &event)
{
if (event.type == UPDATE_PROGRESS)
{
m_pbProgress->SetValue(event.info->precent);
Refresh(false);
}
}
|
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 I guess would be create a named pipe, ShellExecute my own program with a special argument, and then shove all the data that it will need to perform the operation down the pipe. If there are any better suggestions then this I would be glad to hear them.
Thanks for any input.
|
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 following response:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>IIS 7.0 Detailed Error - 400.0 - Bad Request</title>
<style type="text/css">
<!
Does anyone have any ideas what might be happening?
EDIT: more info, when trying to connect to another server in the office (which I can connect to fine using a browser) I'm getting a response of "Bad Request" and no more.
The function making the call is:
#import "msxml3.dll"
BOOL HTTPGet(LPCTSTR URL, CString &Response, long Timeout, BOOL ForceNoCache )
{
BOOL ret = FALSE;
MSXML2::IXMLHTTPRequestPtr rp;
//MSXML2::IServerXMLHTTPRequestPtr rp;
try
{
HRESULT hr = rp.CreateInstance( __uuidof( MSXML2::XMLHTTP ) );
//HRESULT hr = rp.CreateInstance( __uuidof( MSXML2::ServerXMLHTTP30 ) );
if( SUCCEEDED( hr ) )
{
rp->open( "GET" , URL );
if( ForceNoCache )
rp->setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 1970 00:00:00 GMT" );
rp->send();
for( DWORD tc = GetTickCount() ; rp->readyState != 4 && GetTickCount() < tc + Timeout ; )
{
Sleep( 50 );
//WaitMessage();
for( MSG msg ; PeekMessage( &msg, 0, 0, 0, PM_REMOVE ) ; )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
if( rp->readyState == 4 )
{
Response = (LPCSTR)rp->responseText;
ret = TRUE;
}
else
Response = "Timed out";
}
}
catch( CException &e )
{
char err[ 2048 ];
if( e.GetErrorMessage( err , sizeof( err ) ) )
Response = err;
else
Response = "Unhandled exception";
}
catch( _com_error &e )
{
Response = e.ErrorMessage();
}
catch( ... )
{
Response = "Unhandled exception";
}
return ret;
}
EDIT2:
The function works correctly when ForceNocache set to false making the If-Modified-Since header the problem... I'll start up a new question if I can't work out why this isn't liked (by iis 7) but if someone here can point me in the right direction it will save some noise.
Thanks for all your help.
|
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 getting:
error C2228: left of '.reserve' must have class/struct/union
I'm creating a vector using the new operator so that it outlives the function where it is created. This therefore gives me back a pointer to that vector on the heap rather than an actual vector object itself. therefore it won't let me carry out any .reserve() of push_backs.
I can't see a way around it, can anyone help?
|
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->push_back(pArray[f]);
}
|
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: when accepting strings as parameters, should I receive them as const std::string& or const char*?
Thanks.
|
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 his conservative "only pay for what you use" dictum, would have permitted an obvious performance killer into the language. Higher abstraction is good.
|
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 for a the CRTP base class, then it's easy, I can just write:
namespace std { namespace tr1 {
template <typename Derived>
struct hash<CRTPBase<Derived> >
{
size_t operator()(const CRTPBase<Derived> & base) const
{
return base.hash();
}
};
} }
But this specialization doesn't match actual derived classes, only CRTPBase<Derived>. What I want is a way of writing a partial specialization for Derived if and only if it derives from CRTPBase<Derived>. My pseudo-code is
namespace std { namespace tr1 {
template <typename Derived>
struct hash<typename boost::enable_if<std::tr1::is_base_of<CRTPBase<Derived>, Derived>,
Derived>::type>
{
size_t operator()(const CRTPBase<Derived> & base) const
{
return base.hash();
}
};
} }
...but that doesn't work because the compiler can't tell that enable_if<condition, Derived>::type is Derived. If I could change std::tr1::hash, I'd just add another dummy template parameter to use boost::enable_if, as recommended by the enable_if documentation, but that's obviously not a very good solution. Is there a way around this problem? Do I have to specify a custom hash template on every unordered_set or unordered_map I create, or fully specialize hash for every derived class?
|
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
template<> struct X<DummyF1> : CRTPBase< X<DummyF1> > {
int a1;
};
template<> struct X<DummyF2> : CRTPBase< X<DummyF2> > {
int b1;
};
// typedefs
typedef X<DummyF1> F1;
typedef X<DummyF2> F2;
typedef DummyF3 F3; // Does not work
namespace std { namespace tr1 {
template<class T>
struct hash< X<T> > {
size_t operator()(const CRTPBase< X<T> > & base) const
{
return base.hash();
}
};
}} // namespace tr1 // namespace std
//
// Second case
struct DummyS1 : CRTPBase <DummyS1> {
int m1;
};
//
template<typename T>
struct Y : T {};
//
typedef Y<DummyS1> S1;
namespace std { namespace tr1 {
template<class T>
struct hash< Y<T> > {
size_t operator()(const CRTPBase<T> & base) const
{
return base.hash();
}
};
}} // namespace tr1 // namespace std
void main1()
{
using std::tr1::hash;
F1 f1;
F2 f2;
F3 f3;
hash<F1> hf1; size_t v1 = hf1(f1); // custom hash functor
hash<F2> hf2; size_t v2 = hf2(f2); // custom hash functor
hash<F3> hf3; size_t v3 = hf3(f3); // error: standard hash functor
S1 s1;
hash<S1> hs1; size_t w1 = hs1(s1); // custom hash functor
}
|
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 debugging under XCode?
All done in C++ and boost.asio on Mac OS X 10.5 with XCode 3.1.2.
|
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 create or edit any files, they will be owned by root, which means that you'll have to chown them before you can edit them as your normal user first.
I'd love a way for Xcode to say "Launch process as root", but as far as I know, no such functionality is available.
Note that you can also run the application within the command-line debugger gdb to debug your application. Run
>> sudo gdb /path/to/my/application
Then you could keep Xcode open, modify at will, and debug your program within gdb. This is what I generally do.
EDIT: Readers from the future: see the answer from Alexander Stavonin; it talks about how to do this. If you're okay with ssh keys and enabling the root user on your system, his answer is the way to go.
|
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++), but I'm not sure if it is guaranteed to work.
|
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, which do return the iterator, so if you are working in template land you can use them to advance a generic iterator and still have clean code.
|
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 instance of class TFrameFooBar using factory, I get this Exception:
Project gymAce raised EResNotFound with message "Resource TFrameFooBar not found" .
This looks bit like an IDE issue.
Does anyone know a workaround for this?
|
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 and delete each element. My question is, how can i delete the array when I'm done using reportData, so that I do not have any memory leaks?
Report.h
class REPORTAPI ReportData {
public:
ReportData()
{
}
virtual ~ReportData()
{
printf("Starting ReportData Delete\n");
for (list<FileData*>::iterator i = ReportFileData.begin(), e = ReportFileData.end(); i != e; )
{
list<FileData*>::iterator tmp(i++);
delete *tmp;
ReportFileData.erase(tmp);
}
for (list<SupressionData*>::iterator i = ReportSupressionData.begin(), e = ReportSupressionData.end(); i != e; )
{
list<SupressionData*>::iterator tmp(i++);
delete *tmp;
ReportSupressionData.erase(tmp);
}
ReportFileData.clear();
ReportSupressionData.clear();
printf("Finished ReportData Delete\n");
}
list<FileData *> ReportFileData;
list<SupressionData *> ReportSupressionData;
}
extern "C" __declspec(dllexport) FileData* __stdcall createFileData(string fileName, long recordCount, long addPageCount)
{
return new FileData(fileName, recordCount, addPageCount);
}
Main.cpp
ReportData *reportData = createrd();
if (reportData != NULL)
{
CreateFileDataFunc createfd (reinterpret_cast<CreateFileDataFunc>(GetProcAddress (dll, "createFileData")));
const int num_files = 5;
FileData *fileData[num_files];
char buff[256] = {'\0'};
for (int i = 0; i < num_files; i++)
{
sprintf(buff, "test: %d", i);
fileData[i] = createfd(buff, 1, 1);
reportData->ReportFileData.push_back(fileData[i]);
}
delete reportData;
reportData = NULL;
delete [] fileData; // this is throwing an access violation error:
//EAccessViolation: 'Access violation at address 326025AF. Write of address 00000008'.
}
--- I removed the delete oprations from the ReportData dtor
and I'm now looping and deleting:
for(int i = 0; i < num_files; i++)
{
delete fileData[i];
}
This is easier to understand then having to rely on a separate object's dtor to clean up memory.
|
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_from_queue();
}
// producer
void push(data)
{
//<--- will a block ever happen here?
boost::mutex::scoped_lock lock(access);
// add data to queue
cond.notify_one();
}
Let's say I have a thread pool for(;;) loop and I have read() being called from a thread in this pool. Then I process data on it. And I call push() with some external thread. My question is, can that external thread ever block on its call to push(data)?
|
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) by your external thread will only block temporarily up until .wait() is called.
See the boost documentation on the condition's wait function.
|
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 the following code:
byte* pTempBuffer2[3];
try
{
//size_t nBufSize = nBandBytes*m_nBandCount;
pTempBuffer2[0] = new byte[nBandBytes];
pTempBuffer2[1] = new byte[nBandBytes];
pTempBuffer2[2] = new byte[nBandBytes];
}
catch (std::bad_alloc)
{
// If we didn't get the memory just don't buffer and we will get data one
// piece at a time.
return;
}
I was hoping that I would be able to allocate memory until the app reached the 4 gigabyte limit of 32 bit addressing. However, when nBandBytes is 466,560,000 the new throws std::bad_alloc on the second try. At this stage, the working set (memory) value for the process is 665,232 K So, it I don't seem to be able to get even a gig of memory allocated.
There has been some mention of a 2 gig limit for applications in 32 bit Windows which may be extended to 3 gig with the /3GB switch for win32. This is good advice under that environment, but not relevant to this case.
How much memory should you be able to allocate under the 64 bit OS with a 32 bit application?
|
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 one big contiguous chunk. It might be several smaller chunks of a couple of hundred MB each.
If you compile with the LargeAddressAware flag, 64-bit Windows will let you use the full 4GB address space, which should help a bit, but in general,
you shouldn't assume that the available memory is contiguous. You should be able to work with multiple smaller allocations rather than a few big ones, and
You should compile it as a 64-bit application if you need a lot of memory.
|
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 each ID* to FOO* thus having something like that
map myMap; which I think is kind of ugly and redundant.
Please suggest
|
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(); // compiler complains here.
//...
}
Now while the error is pretty obvious once you know it I was wondering if there is any sensible use for this kind of local function declaration except that you can do it -- especially since there is no way to define such a local function in the same block; you have to define it elsewhere.
I think that Java-style local classes are a pretty nice feature which I tend to use often, especially the anonymous sort. Even local C++ classes (which can have inline-defined member functions) have some use. But this local function declaration without definition thing seems very awkward to me. Is it just a C-legacy or is there some deeper use case which I am not aware of?
Edit for the non-believers: C c() is not a function pointer declaration.
This program
int main()
{
void g();
cout << "Hello ";
g();
return 0;
}
void g()
{
cout << "world." << endl;
}
outputs Hello world. This program
void fun()
{
cout << "world." << endl;
}
int main()
{
void g();
g = fun;
cout << "Hello ";
g();
return 0;
}
does not compile. gcc complains:
error: cannot convert 'void ()()' to 'void ()()' in assignment
comeau:
error: expression must be a modifiable lvalue
|
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 of its internal implementation, e.g. because I may want to change or vary it. So I expose accessor and mutator functions for its elements, and a traversal function to iterate over the elements. The traversal function has as its argument a function that operates on an element; the traversal function's task is to execute the argument function on each element and possibly aggregate the results in some way. Now when I call the traversal function, the argument function is usually some specialized operation that depends on local state and therefore should be defined as a local function. Having to push the function, with the variables that contain the local state, outside to be global, or into an inner class created specifically to hold them, is butt ugly. But this is a problem I have with C and Java, not with C++.
|
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 computer I get a message box with a progress bar with the name of "windows socket notification sink". That's the much I can say about it.
|
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 to be managed. Which socket class are you using?
|
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 namespace std;
int main()
{
int t,i, nums[3][4];
for(t=0; t < 3; ++t) {
for(i=0; i < 4; ++i) {
nums[t][i] = (t*4)+i+1; //I don't understand this part/line
cout << nums[t][i] << ' ';
}
cout << '\n';
}
return 0;
}
so here are some questions.
I cannot understand the initialization of the 2D int array nums[3][4]. What separates the (t*4)+i+1, so that the compiler knows what to assign where?
How do I know what values will be stored in the rows and columns, based on what values have been assigned?
Why is there an asterisk?
What are the parentheses around t*4 for?
I understand that initialization two-dimensional arrays look like the following example.
#include <iostream>
using namespace std;
int main() {
char str[3][20] = {{"white" "rabbit"}, {"force"}, {"toad"}}; //initialize 2D character array
cout << str[0][0] << endl; //first letter of white
cout << str[0][5] << endl; //first letter of rabbit
cout << str[1][0] << endl; //first letter of force
cout << str[2][0] << endl; //first letter of toad
return 0;
}
And from what I know, like this in memory.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 w h i t e r a b b i t 0
1 f o r c e 0
2 t o a d 0
Thank you.
|
(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 multiply operator takes precedence over the plus operator anyway.
Also, I couldn't tell from your question if you knew this already or not, but the meaning of rows[t][i] is array notation for accessing rows at row t and column i.
|
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 none, I don't mind writing my own, but I need a good specification. There doesn't seem to be all that much information that I can find via google though, so I need your help.
|
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 clears the dialog and complains that I do not have a valid entry point.
If I save anyway, the entryPoint is empty on the resultant manifest. That makes clickonce fail because there is no valid entrypoint.
I've tried manually creating an entry point as follows:
<entryPoint>
<assemblyIdentity
type='win32'
name='My App'
version='0.9.1.0'
processorArchitecture='msil'
language='en-US'/>
<commandLine
file="app.exe"
parameters="run"/>
</entryPoint>
That doesn't work either.
|
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 can create a shim as described here.
|
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 know the commands to kill the processes, but I am having trouble getting the pids of my children. Does anyone know of a way to do this?
|
#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", parentID, processID) != EOF)
{
printf("PID: %s Parent: %s\n", processID, parentID);
// Check the parentID to see if it that of your process
}
pclose(fp);
return 1;
}
|
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. I can see that LoadLibrary is failing and GetLastError is returning 5 which is "access denied".
now, why would vs be denied access to winmm.dll?
---Begin Original---
I am currently having a serious issue with Visual Studio 2005 SP1 Intellisense in C++. I have an all native solution with on project. Whenever I, or the editor, attempt to invoke intellisense auto-complete pow, Visual Studio crashes. I even tried this with a brand new console app. Ctrl + Space in the empty main and Visual Studio crashes.
I googled for help on this but to no avail. I have tried deleting the ncb file but no luck on that front either.
I am currently working with Intellisense turned off as shown in this article:
Visual Studio 2005 - 'Updating IntelliSense' hang-up
And I have no crashes, but it sure would be nice to have intellisense back
Call stack from a crash dump.
7c812a6b kernel32!RaiseException+0x53
502717a6 msenv!__delayLoadHelper2+0x139
50675186 msenv!_tailMerge_WINMM_dll+0xd
505ac3c3 msenv!CTextViewIntellisenseHost::UpdateCompletionStatus+0x1a7
505acb50 msenv!CEditView::UpdateCompletionStatus+0x30
505dcfad msenv!CEditView::CViewInterfaceWrapper::UpdateCompletionStatus+0x2a
02ae47fc vcpkg!CCompletionList::DoCompletion+0x444
02ade2ce vcpkg!CAutoComplete::PostProcess+0x240
02ade07f vcpkg!CAutoComplete::OnACParseDone+0x3e
02adac2d vcpkg!CMemberListWorkItem::OnCompleted+0x9d
029eb4e3 vcpkg!CWorkItem::ProcessPendingWorkItemCompletedCalls+0x117
029f8b4f vcpkg!CParserManager::OnIdle+0x183
0299961a vcpkg!CVCPackage::OnIdle+0x48
5014b288 msenv!ATL::CComAggObject<CTextBuffer>::QueryInterface+0x43
5a9d2394 VCProject!ATL::CComPtr<IOleInPlaceFrame>::~CComPtr<IOleInPlaceFrame>+0x24
5a9d2880 VCProject!ATL::CComObject<CVCArchy>::Release+0x10
774fd420 ole32!CRetailMalloc_GetSize+0x21
5009422b msenv!CMsoCMHandler::FContinueIdle+0x23
5009422b msenv!CMsoCMHandler::FContinueIdle+0x23
|
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 play this sound winmm.dll must be loaded up, which is located c:\windows\system32\winmm.dll.
I suppose through debugging foray winmm.dll symbols were downloaded to a FOLDER called C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\winmm.dll. Of course this folder looked mighty tasty to Visual Studio, so when it tried to load the winmm.dll folder as a dll file POW!!!
I deleted the folder, and some other .dll folders :) and all is well.
Thanks for your help.
|
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 referencing something equal to fseek. Right now the files that I am reading in are 16GB+ CSV files with the expectation of at least double that.
Without any external libraries what is the most straightforward method for achieving a similar structure as with the fseek/ftell pair? My application right now works using the standard GCC/G++ libraries for 4.x.
|
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 large file support on linux:
Compile your programs with "gcc -D_FILE_OFFSET_BITS=64". This forces all file access calls to use the 64 bit variants. Several types change also, e.g. off_t becomes off64_t. It's therefore important to always use the correct types and to not use e.g. int instead of off_t. For portability with other platforms you should use getconf LFS_CFLAGS which will return -D_FILE_OFFSET_BITS=64 on Linux platforms but might return something else on e.g. Solaris. For linking, you should use the link flags that are reported via getconf LFS_LDFLAGS. On Linux systems, you do not need special link flags.
Define _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE. With these defines you can use the LFS functions like open64 directly.
Use the O_LARGEFILE flag with open to operate on large files.
|
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 settings.
The interface (i.e. the only exported function) simply returns a pointer to an instance of the Class that I actually need to call. I can successfully call this, get the pointer and call the first function that I need to (an "init" function).
When I come to call the function that actually does the processing I require, I'm intermittently getting a "0xC0000005: Access violation reading location...." error. That is, I run the program - it works successfully and exits - I try to run it again (changing nothing - all parameters are hard coded) and get the error (and continue to do so).
I can't consistently recreate the problem but I'm beginning to think that it may be something to do with the DLL not being unloaded properly - after getting the error on one occasion I tried deleting the DLL and was told by Windows that it was in use. That said, on another occasion I was able to delete the DLL after getting the error, copy it back, then still got the error on the next run.
Should the DLL be correctly unloaded when my .exe finishes? Would I be better off trying to explicitly load/unload the DLL rather than doing it implicitly?
Any other help or advice greatly appreciated.
|
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 race condition. This could be one that's exposed if the DLL has been cached, causing the timing to change. That would explain why your first run didn't fail but subsequent ones did.
I think it's also possible that the DLL didn't release its lock on some file. If there is some file you know is accessed by this DLL, try checking to see if that file is locked after the process ends.
Also, get this in a debugger. Turn on first-chance exceptions in visual studio and look at the callstack where the AV is happening, and post it here.
|
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 to EXACTLY 1023. My hunch is that there's a problem.
This is the new routine
void NewRoutine(char *cmdd){
GSM.print(cmdd);
GSM.print(26, BYTE);
GSM.print(endl); // <-- added later
Serial.print(availableMemory());
}
And this is the MemoryCheck Routine
int availableMemory() {
int size = 1024;
byte *buf;
while ((buf = (byte *) malloc(--size)) == NULL);
free(buf);
return size;
}
Please note this: First, it didn't work. After I added the endl command, it worked magically, but then I noticed the memory issue.
Anyone got ideas for a workaround?
|
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 the GSM class here - it probably holds the data (cmdd + 26) in an internal buffer which is flushed on a newline. As soon as you added your endl call, you're probably getting the full memory back from the buffer.
How large is your command? My guess is that it (or the full set of them) is probably around 700 bytes...
|
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(); //allocate and construct
aWidget->~Object(); //destroy and DON'T deallocate
I know I could just delete the object, but I don't want to. I want to keep the allocated memory handy as an important optimization.
Thanks!
|
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 where two shared libraries referenced an object. We changed the definition to add child objects which needed freeing. We recompiled the first shared library which contained the object definition.
HOWEVER, the second shared library was not recompiled. This means that it did not know of the newly added virtual object definition. Delete's invoked from the second shared library simply called free, and did not invoke the virtual destructor chain. Result was a nasty memory leak.
|
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 *argv[]) {
int status;
struct stat st_buf;
// Ensure argument passed.
if (argc != 2) {
printf ("Usage: progName <fileSpec>\n");
printf (" where <fileSpec> is the file to check.\n");
return 1;
}
// Get the status of the file system object.
status = stat (argv[1], &st_buf);
if (status != 0) {
printf ("Error, errno = %d\n", errno);
return 1;
}
// Tell us what it is then exit.
if (S_ISREG (st_buf.st_mode)) {
printf ("%s is a regular file.\n", argv[1]);
}
if (S_ISDIR (st_buf.st_mode)) {
printf ("%s is a directory.\n", argv[1]);
}
return 0;
}
Sample runs are shown here:
pax> vi progName.c ; gcc -o progName progName.c ; ./progName
Usage: progName
where is the file to check.
pax> ./progName /home
/home is a directory.
pax> ./progName .profile
.profile is a regular file.
pax> ./progName /no_such_file
Error, errno = 2
|
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>,
generate_mpl_vector<fusion::vector<int, char> >::type >));
I need generate_fusion_vector and generate_mpl_vector metafunctions.
I can write my own metafunctions, but i suspect that they already exist.
I had an experience of generating fusion::map with help result_of::as_map before, but in current boost(trunk, 1.39 also) such error occur:
D:\Libraries\boost_trunk\boost/fusion/sequence/intrinsic/size.hpp(56) : error C2903: 'apply' : symbol is neither a class template nor a function template
D:\Libraries\boost_trunk\boost/fusion/container/vector/convert.hpp(23) : see reference to class template instantiation 'boost::fusion::result_of::size' being compiled
with
[
Sequence=boost::mpl::vector
]
temp.cpp(71) : see reference to class template instantiation 'boost::fusion::result_of::as_vector' being compiled
I don't understand what is going on?
|
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 compatibility in fusion.
#include <boost/fusion/adapted/mpl.hpp>
#include <boost/fusion/include/mpl.hpp>
|
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 necessarily, sql might be overkill)
i was thinking about qt, boost, tokyo cabinet and/or sqlite; what else? what is "best suited"?
i would like to keep platform customization and overall execution footprint at minimum...
thank you in advance
|
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 easier to use C runtime functions than Boost.Filesystem).
|
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.lib).
But if I do this there are all kinds of unresolved external errors. So I would like to keep using both libraries.
Is there any way to tell the linker that I want to use the _atoi function in libc.lib and not in msvcrt.lib (or the other way around)?
Any help or direction would be great.
|
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); second definition ignored
Of course you will need to use this option with care as it can generate an application which won't work in some cases, but here it probably doesn't do any harm (I hope).
Thank you for the other replies, but that didn't seem to be an option in my particular case.
|
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, please specify how to access the code present in tlb file from C++.
|
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 implementation files to be built with your project and the header files to be included, so this is lots of magic stuff right there.
Then, you get a whole lot of typedefs for smart pointer wrappers for the types and objects defined in the type library. For example, if there was a CoClass called Application which implemented the interface IApplication, you could do this:
ApplicationPtr app(__uuidof(Application));
This would cause at run time, the coclass application to be created and bound to the variable app, and you can call on it like so:
app->DoSomeCoolStuff();
Error handling is done by checking the result of COM calls, and throwing the appropriate _com_error exception as necessary so this implies you need to write exception safely.
|
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 exceptions are correctly caught/rethrown? For example a Visual C++ plugin or a different C++ compiler.
PS. I want the compiler to check whether exceptions are correctly caught, otherwise you end up in a situation where you have to put a catch around every single function call you make, even if they explicitly state they won't throw anything.
Update: the Visual C++ compiler does show a warning when throwing in a function marked with throw(). This is great, but regrettably, the warning doesn't show up when you call a subroutine that might throw. For example:
void f() throw(int) { throw int(13); }
void h() throw() { g(); } //no warning here!
|
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. Better to simply not bother.
|
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 debugability?
|
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 )
{
filename = filename.Mid(filenameStart);
}
}
return filename;
}
CString GetCallingVersionNumber(const CString& filename)
{
DWORD fileHandle, fileVersionInfoSize;
UINT bufferLength;
LPTSTR lpData;
VS_FIXEDFILEINFO *pFileInfo;
fileVersionInfoSize = GetFileVersionInfoSize(filename, &fileHandle);
if( !fileVersionInfoSize )
{
return "";
}
lpData = new TCHAR[fileVersionInfoSize];
if( !lpData )
{
return "";
}
if( !GetFileVersionInfo(filename, fileHandle, fileVersionInfoSize, lpData) )
{
delete [] lpData;
return "";
}
if( VerQueryValue(lpData, "\\", (LPVOID*)&pFileInfo, (PUINT)&bufferLength) )
{
WORD majorVersion = HIWORD(pFileInfo->dwFileVersionMS);
WORD minorVersion = LOWORD(pFileInfo->dwFileVersionMS);
WORD buildNumber = HIWORD(pFileInfo->dwFileVersionLS);
WORD revisionNumber = LOWORD(pFileInfo->dwFileVersionLS);
CString fileVersion;
fileVersion.Format("%d.%d.%d.%d", majorVersion, minorVersion, buildNumber, revisionNumber);
delete [] lpData;
return fileVersion;
}
delete [] lpData;
return "";
}
|
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 instance? In other words, how to make clear on which pointer delete has to be called?
Note: In the above example this is not hard to see, as it is a very short piece of code. However, when the pointer is duplicated and passed around a lot, this can become unclear.
|
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 design that can give you this information. Since you (and your coworkers) are writing the code you can always make sure that this design is enforced during implementation. This of course means that everyone has to follow these "rules".
This is one reason why a common coding convention is so important. So you can read your own and other peoples code and understand it.
|
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 easy to derive exceptions whose what() does return NULL, but I'm not sure how such things fit into standards conformance. Certainly, if you are implementing what() in your own exception class, I would consider it very bad practice to allow it to return NULL.
More:
For a further question addressing whether what() can return NULL, and similar exciting issues, please see Extending the C++ Standard Library by inheritance?
|
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 criteria, perhaps with using functor and for_each or erase algorithm ?
|
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 affects the first character of the string rather than adding unwanted rubbish onto the end? And how come the program's output is at odds with the way the string looks in the debugger ("Test\n", as I'd expect)?
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
const int bufferSize = 1024;
ifstream input( "test.txt", ios::in | ios::binary );
vector<char> vecBuffer( bufferSize );
input.getline( &vecBuffer[0], bufferSize );
string strResult( vecBuffer.begin(), vecBuffer.begin() + input.gcount() );
cout << strResult << "\n";
return 0;
}
|
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 getline function strips off the \n, but leaves the \r in place.
You then transfer the vecBuffer to a string variable, but use the gcount function from input, meaning you will get one char too much, because the input variable still contains the \n, and the vecBuffer does not.
The resulting strResult is:
- strResult "Test"
[0] 84 'T' char
[1] 101 'e' char
[2] 115 's' char
[3] 116 't' char
[4] 13 '␍' char
[5] 0 char
So then "Test" is printed, followed by a carriage return (puts the cursor back at the start of the line), a null character (overwriting the T), and finally the \n, which correctly puts the cursor on the new line.
So you either have to strip out the \r, or write a function that gets the string length directly from vecBuffer, checking for null characters.
|
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 function eof() would tell me. So I did something like this (very generalized):
for(int i = 0; i < max && !file.eof(); i++)
{
file.read(mything, sizeof(mything));
}
The problem came because of what is explained later on the page linked above (which I failed to read initially, thanks to the misleading first paragraph):
Conversely, the stream does not go into EOF state if there happens to be any whitespace after the last token, but trying to read another token will still fail. Therefore, the EOF flag cannot be used as a test in a loop intended to read all stream contents until EOF. Instead, one should check for the fail condition after an attempt to read.
So I changed, and now my loop checks against file.fail() rather than file.eof(), and I understand HOW eof() works. My question is, why does it work that way? Are there situations where this is desirable? It seems to me that once you've passed EOF, you've passed EOF and eof() should return true.
UPDATE
Thanks for the responses, I think I've got it. The only operation I'm performing is read(), and I immediately check for fail(), so I think I'm okay. Now, my question is, what would I use eof() for?
|
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 call ReadFile but I believe that the functionality is similar).
From the read manpage "RETURN VALUE" section (emphasis added):
On success, the number of bytes read
is returned (zero indicates end of
file), and the file position is
advanced by this number. It is not an
error if this number is smaller than
the number of bytes requested; this
may happen for example because fewer
bytes are actually available right now
(maybe because we were close to
end-of-file, or because we are reading
from a pipe, or from a terminal), or
because read() was interrupted by a
signal. On error, -1 is returned, and
errno is set appropriately. In this
case it is left unspecified whether
the file position (if any) changes.
BTW: a good way to write what you wanted would be like this:
T something;
while(file.read(something, sizeof(something))) {
// process your 'something'
}
this works because file.read (like many members of iostream) return a reference to the iostream itself. All of which have an operator overloaded to allow testing the stream state. Similarly to read from std::cin, while(std::cin >> x) { ... } works as well.
EDIT: you should know that testing vs. fail can be equally wrong for the same reason. From the page you linked to fail() returns if the previous operation failed. Which means you need to perform a read or other relevant operation before testing it.
|
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.
EDIT: If anyone knows how to make that picture imbed inline, go for it... I couldn't get it.
|
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' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif
If that code is there(and I think it should be there) you should check that you have compiled UNICODE version( with _UNICODE defined).
More details about enabling Vista Common Controls you could read in MSDN Article.
|
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 examined with the OLE Object Viewer.
We would rather not register the service on the build server, if possible. Further, debug builds cannot register the COM object as a service, since this makes debugging in general, and startup code in particular, more difficult (can't use F5 - Start Debugging).
What should I look for in order to get this working? Do I need to register just the TypeLib? If so, why would COMInterop insist on having the service or TLB registered in order to build correctly (and, is there a command-line tool for this on Win2003 with VS2005)?
If I recall correctly, once apon a time I built a C# web service which referenced the Win2003 firewall COM object, but we built it on Win2000 (which does not have such a thing) simply by referencing the TLB file with no registration required, so I don't understand why this should be a problem now.
|
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 are more difficult to describe in this manner due to the complexities of multiple inheritance, and the fact that C++ supports interface-only inheritance in a somewhat clumsy way (compared to java, etc), but it's there (and could be improved).
And then templates came into play, along with the STL. The STL seems to take the classical OOP concepts and flush them down the drain, using templates instead.
There should be a distinction between cases when templates are used to generalize types where the types themselves are irrelevant for the operation of the template (containers, for examples). Having a vector<int> makes perfect sense.
However, in many other cases (iterators and algorithms), templated types are supposed to follow a "concept" (Input Iterator, Forward Iterator, etc...) where the actual details of the concept are defined entirely by the implementation of the template function/class, and not by the class of the type used with the template, which is a somewhat anti-usage of OOP.
For example, you can tell the function:
void MyFunc(ForwardIterator<...> *I);
Update: As it was unclear in the original question, ForwardIterator is ok to be templated itself to allow any ForwardIterator type. The contrary is having ForwardIterator as a concept.
expects a Forward Iterator only by looking at its definition, where you'd need either to look at the implementation or the documentation for:
template <typename Type> void MyFunc(Type *I);
Two claims I can make in favor of using templates: 1. Compiled code can be made more efficient, by recompiling the template for each used type, instead of using dynamic dispatch (mostly via vtables). 2. And the fact that templates can be used with native types.
However, I am looking for a more profound reason for abandoning classic OOP in favor of templating for the STL?
|
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 for OOP code, but it also had a turing-complete template language overlaid, it allowed compile-time metaprogramming, and people had discovered generic programming. Suddenly, OOP just didn't seem all that important. Not when we can write simpler, more concise and more efficient code by using techniques available through templates and generic programming.
OOP is not the holy grail. It's a cute idea, and it was quite an improvement over procedural languages back in the 70's when it was invented. But it's honestly not all it's cracked up to be. In many cases it is clumsy and verbose and it doesn't really promote reusable code or modularity.
That is why the C++ community is today far more interested in generic programming, and why everyone is finally starting to realize that functional programming is quite clever as well. OOP on its own just isn't a pretty sight.
Try drawing a dependency graph of a hypothetical "OOP-ified" STL. How many classes would have to know about each other? There would be a lot of dependencies. Would you be able to include just the vector header, without also getting iterator or even iostream pulled in? The STL makes this easy. A vector knows about the iterator type it defines, and that's all. The STL algorithms know nothing. They don't even need to include an iterator header, even though they all accept iterators as parameters. Which is more modular then?
The STL may not follow the rules of OOP as Java defines it, but doesn't it achieve the goals of OOP? Doesn't it achieve reusability, low coupling, modularity and encapsulation?
And doesn't it achieve these goals better than an OOP-ified version would?
As for why the STL was adopted into the language, several things happened that led to the STL.
First, templates were added to C++. They were added for much the same reason that generics were added to .NET. It seemed a good idea to be able to write stuff like "containers of a type T" without throwing away type safety. Of course, the implementation they settled on was quite a lot more complex and powerful.
Then people discovered that the template mechanism they had added was even more powerful than expected. And someone started experimenting with using templates to write a more generic library. One inspired by functional programming, and one which used all the new capabilities of C++.
He presented it to the C++ language committee, who took quite a while to grow used to it because it looked so strange and different, but ultimately realized that it worked better than the traditional OOP equivalents they'd have to include otherwise. So they made a few adjustments to it, and adopted it into the standard library.
It wasn't an ideological choice, it wasn't a political choice of "do we want to be OOP or not", but a very pragmatic one. They evaluated the library, and saw that it worked very well.
In any case, both of the reasons you mention for favoring the STL are absolutely essential.
The C++ standard library has to be efficient. If it is less efficient than, say, the equivalent hand-rolled C code, then people would not use it. That would lower productivity, increase the likelihood of bugs, and overall just be a bad idea.
And the STL has to work with primitive types, because primitive types are all you have in C, and they're a major part of both languages. If the STL did not work with native arrays, it would be useless.
Your question has a strong assumption that OOP is "best". I'm curious to hear why. You ask why they "abandoned classical OOP". I'm wondering why they should have stuck with it. Which advantages would it have had?
|
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 coded. The server specifies the port explicitly:
boost::asio::io_service io_service;
tcp::endpoint endpoint(tcp::v4(), 13);
tcp::acceptor acceptor(io_service, endpoint);
Port 13 is a well-known port for a "daytime" service.
The client example connects by specifying a host and the service name:
tcp::iostream s(argv[1], "daytime");
For my own application, I would like to put the server on an arbitrary port and connect by number as shown below:
Server:
boost::asio::io_service io_service;
tcp::endpoint endpoint(tcp::v4(), port);
tcp::acceptor acceptor(io_service, endpoint);
acceptor.accept(*this->socketStream.rdbuf());
...
Client:
boost::asio::ip::tcp::iostream sockStream;
...
sockStream.connect("localhost", port);
...
If, in the client, I try to specify the port number directly (instead of a service by name), the stream fails to connect. Is there a way to do this? It is not clear to me what the arguments to connect could/should be.
2.) What is the preferred way to test the success of a call to iostream::connect?
The function returns void, and no exception is thrown. The only method I've devised so far is to test the stream.fail() and/or stream.good(). Is this the way to do it, or is there some other method.
Advice on one or both of these would be appreciated. Also, if I am overlooking pertinent documentation and/or examples those would be nice. So far I haven't been able to answer these questions by reading the library docs or searching the 'net.
|
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::system::error_code object which will tell you if it connected successfully.
|
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 write something like this,
ArrayList<Double> dummy = new ArrayList<Double>();
My question, why should it be an Object, what is so hard technically to include primitive types when talking about Generics ?
|
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: the generic type information is lost during run-time. This was for compatibility reasons, because generics were added fairly late in Java's life. This means that, run-time, an ArrayList<String> is effectively an ArrayList<Object> (or better: just ArrayList that expects and returns Object in all of its methods) that automatically casts to String when you retrieve a value.
But since int doesn't derive from Object, you can't put it in an ArrayList that expects (at runtime) Object and you can't cast an Object to int either. This means that the primitive int must be wrapped into a type that does inherit from Object, like Integer.
C# for example, works differently. Generics in C# are also enforced at runtime and no boxing is required with a List<int>. Boxing in C# only happens when you try to store a value type like int in a reference type variable like object. Since int in C# inherits from Object in C#, writing object obj = 2 is perfectly valid, however the int will be boxed, which is done automatically by the compiler (no Integer reference type is exposed to the user or anything).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.