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
3,261,596
3,261,698
Why are "out of source" builds not the default?
I just found out recently that you can configure Visual Studio (but this question is the same for any compiler) to dump the intermediate .o files into a separate folder outside of the source tree, instead of alongside each individual project. That makes it easy to clean the project up to archive to zip or something alo...
This is the default in Visual Studio, and has been for quite some time (at least as far back as VC++ 6). The intermediate directory defaults to the same as the output directory, not the source directory. This means that all object files are placed alongside the final output. In fact, it requires some jiggery-pokery if ...
3,261,608
3,261,638
C++ Portability between Windows and Linux
I have a question about writing programs to be portable between windows and linux. Recently I have realized that if you write a program that uses any sort of external library, if that library doesn't have a linux version (or a windows version when developing in linux) then you're screwed. Here then is my question: if I...
you will have to recompile all libraries for different operating systems. The binary formats for libraries vary from operating system to operating system. More importantly, even if you aren't using libraries, you need to recompile for the simple reason that the different operating systems have different syscall conve...
3,261,618
3,275,955
Simple multithreaded server in C++?
I want to write a simple server application that will take commands from a client application and run those commands in separate threads. I was looking at the server class in dlib. Does anyone have experience using this? How does it compare to using Boost's Asio? Example of server in dlib Examples of client/serv...
Boost Asio will do this quite easily. Have a look at the examples in the Highscore tutorial, which shows how to use Boost for asynchronous input/output with multithreading. #include <boost/asio.hpp> #include <boost/thread.hpp> #include <iostream> void handler1(const boost::system::error_code &ec) { std::cout <...
3,261,676
3,262,182
How to make QDialogButtonBox NOT close its parent QDialog?
I have a QDialog with a QDialogButtonBox widget, and I've connected the button box's accepted signal to a slot in my QDialog subclass, like so: void MyDialog::on_buttonBox_accepted() { QString errorString = this->inputErrorString(); if (errorString.isEmpty()) { // Do work here // code code c...
You can implement MyDialog::accept(). The function is virtual in QDialog.
3,261,694
3,261,770
Why base class destructor (virtual) is called when a derived class object is deleted?
A difference between a destructor (of course also the constructor) and other member functions is that, if a regular member function has a body at the derived class, only the version at Derived class gets executed. Whereas in case of destructors, both derived as well as base class versions get executed? It will be great...
The Standard says After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X’s direct non-variant members,the destructors for X’s direct base classes and, if X is the type of the most derived class (12.6.2), its de...
3,262,020
3,262,050
Shorter Calls/Names Without Using Defines
Simple question, how do I shorten a call/name without using defines. For example, I have a singleton that I have to call that is within a namespace (I cannot use using namespace blabla because it is not allowed) like so: MyFW::GameRoot::Instance()->DoSomething(); Now I can assign that to a variable, which works somewh...
If you want to ease access across multiple functions, just use a helper function: namespace { MyFW::GameRoot* root() { return MyFW::GameRoot::Instance(); } } // ... root()->DoSomething(); Two characters more, but it with comes type-safety included.
3,262,316
3,262,538
question about second pointers
i am using c++ and i have some trouble about pointers i know that if we declare some variable int t=7; int *p=&t; *p gives adress of variable t but in c++ here also definition of **s why it is used ?i have read it but i have some misunderstanding please can anybody give me example how use?let take about given ...
First of all *p will give you the value of variable t and not the address of t. Only 'p' will give you the address of t. Essentially every address is just an integer number. If you are compiling for 32-bit architecture then it will be 32-bit long number and if you are compiling for 64-bit then it will be 64-bit long. T...
3,262,586
3,273,365
access Error table in msi
Basically I am trying to make a localized copy of an existing English msi file. If I rebuild the MSI with proper wxl file n code page it takes a long time, and I need my installer in more than 25 languages. I am able to access all other local strings like text on controls n all but I couldn't find the way to change the...
If you don't add an Error table to the MSI yourself, the Windows Installer falls back to it's own error messages (that follow the user language choice, IIRC). If you want an Error table, you have to add it yourself.
3,262,811
3,262,906
What is Single and Double Dispatch?
i have wrote the visitor pattern as follow but i don't understand what is single and double dispatch. AFAIK, single dispatch is invoke a method based on caller type where double dispatch is invoke a method based on caller type and argument type. I guess double dispatch is happen in single class hierarchy but why visi...
In short, single dispatch is when a method is polymorphic on the type of one parameter (including the implicit this). Double dispatch is polymorphism on two parameters. The typical example for the first one is a standard virtual method, which is polymorphic on the containing object's type. And the second one can be imp...
3,262,851
3,262,934
The boost "signature" question
I'm trying to figure out how could many boost classes be able to accept a function signature as template argument and then "extract" from there the result type, first argument type and so on. template <class Signature> class myfunction_ptr { Signature* fn_ptr; public: typedef /*something*/ result_type; // How c...
At the core its just specialization and repetition: template<class S> struct Sig; template<class R> struct Sig<R ()> { typedef R result_type; }; template<class R, class T0> struct Sig<R (T0)> { typedef R result_type; typedef T0 first_type; }; // ...
3,263,135
3,263,378
How to implement final conditions properly?
This is what I'm trying to do (this is a simplification of a real project): int param; int result; void isolated(int p) { param = p; try { // make calculations with "param" and place the // result into "result" process(); } catch (...) { throw "problems.."; } } I can't change the way process() ...
I still don't quite sure how finally is related here, but you could try Boost.ScopeExit if you want to avoid creating a scope guard structure yourself. Example: #include <boost/scope_exit.hpp> #include <cstdio> int isolated(int p) { static bool running = false; if (running) { printf("Throwing %d\n", p)...
3,263,159
3,263,260
Calling SDL_SetVideoMode several times
Is it ok to do the following? SDL_Surface* screen; screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE | SDL_RESIZABLE | SDL_FULLSCREEN ); screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE | SDL_RESIZABLE ); screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HE...
The only way to toggle fullscreen on Windows is to call SDL_SetVideoMode again. You have not to free the screen surface. Be careful, you may lost the hardware surfaces.
3,263,239
3,264,687
Using a union for multiple interpretations of IP address?
At work we have the following construct to enable interpreting an IP address as either an array of 4 bytes, or as a 32-bit integer: union IPv4 { std::uint32_t ip; std::uint8_t data[4]; }; This works fine, but I'm a little worried after reading chapter 97 "Don't use unions to reinterpret representation" of the...
According to the standard, reading a member of a union other than the last one written is undefined behavior. Unions were designed to save space, no for data type conversion. That said, what you are doing will probably work on all mainstream platforms and compilers.
3,263,252
3,263,326
Is typedef just a string replacement in code or somethings else?
I was curious to know how exactly typedef works. typedef struct example identifier; identifier x; In above statement is 'identifier' just replaced (somethings like string replacement) with 'struct example' in code? If no, what does typedef do here? please enlighten!
No, it is not a string replacement - that would be macros. It creates an alias for the type. typedefs are preferred over macros for custom types, in part because they can correctly encode pointer types. typedef char *String_t; #define String_d char * String_t s1, s2; String_d s3, s4; s1, s2, and s3 are all declared a...
3,263,323
3,263,484
C++ read from istream until newline (but not whitespace)
I have a std::istream which refers to matrix data, something like: 0.0 1.0 2.0 3.0 4.0 5.0 Now, in order to assess the number of columns I would like to have some code like: std::vector<double> vec; double x; while( (...something...) && (istream >> x) ) { vec.push_back(x); } //Here vec should contain 0.0, 1.0 and...
Use the peek method to check the next character: while ((istream.peek()!='\n') && (istream>>x))
3,263,457
3,263,490
Can I use a variable to specify the size of a struct member array?
I am trying to represent a HD page in a struct. The code below does not work, because page_size is not a constant. int page_size = 4096; struct page { char data[page_size]; /* some methods */ } Since I am building and randomly accessing arrays of pages, it would be nice if I could treat a page as a fixed length...
Nope. As you've found out, you can't. The compiler needs to know the size of its data structures, reliably and constantly, to do its work. I'm assuming that the page data is not the only content of your struct. You probably have some header / management information about your page in there along with the text. The comm...
3,263,661
3,263,833
Format a date in C++
I have a series of date strings in the format: "30-05-2001" string date1 = "30-05-2001"; I would like to parse the date into Day, Month, Year. Now an easy way of doing this would be just to call the function sscanf. But I'd like to explore other possiblilties and from searching the web the following function from t...
Just in case you want to understand how it works (no blackbox) or if you need the stuff to fly (no function calls) then here are a few tips for you: // 0123456789 char date[] = "30-05-2001"; // DD-MM-YYYY int day, month, year; day = (date[0] - '0') * 10 + (date[1] - '0'); month = (date[3] - '0') * 10 + (...
3,263,743
3,263,969
autoexp.dat not parsing union?
I have an in-place vector class that's defined like so: template<class T> class svectorbase { // ... protected: union { char* m_char; T* m_t; } m_elems; size_t m_maxsize; int m_elemCount; }; template<class T, size_t maxsize> class svector : public svectorbase<T> { protected: ...
You've got a member variable called m_elems in your base class, and another member variable called m_elems in the derived class. The $c.m_elems in $c.m_elems.m_t refers to the derived class's char array, not the base class's union.
3,263,850
3,266,624
will be this initialization syntax valid in upcoming c++0x standard?
Suppose we have following two classes: class Temp{ public: char a; char b; }; class Final{ private: int a; char b; char c; public: Final(Temp in):b(in.a),c(in.b){} //rest of implementation }; can we initialize an object of the Final class with following syntax in upcoming c++0x standard: Final obj(Tem...
C++0x adds uniform initialization like for POD-struct and array types using braces ({}) for all types as well special initializer lists to support variable number of elements/arguments in them just like an array. So your example can be written as: Final obj = { { 'a', 'b' } }; or Final obj { { 'a','a' } };
3,263,854
3,263,906
scoped_ptr for structure with substituted free method
I have a structure typedef struct myStruct_st { int a; }myStruct; It can be created using myStruct * myStruct_new() { printf("Allocate\n"); return new myStruct; } And deleted using static void myStruct_free(myStruct * ptr) { printf("Deallocate\n"); delete ptr; } I want the memory allocated for the struc...
Boost's shared_ptr does pretty much the same thing, in pretty much the same code. #include <boost/shared_ptr.hpp> main() { boost::sshared_ptr<myStruct> ptr_st(myStruct_new(), myStruct_free); ptr_st->a = 11; } But you should consider whether you want to be writing C++ code or C code. You're using some very C...
3,263,873
3,263,943
Question about the volatile keyword
I know that by the volatile keyword, volatile int k=7; we hint the compiler that the variable can be changed at any time but what about a simple int k=7? Can we change it at any time because it is not constant? What is different?
It's used in low level programming with interrupts and so on mostly volatile int count; void test() { while(count< 100) { // do nothing } } // // Interrupt function called by the hardware automatically at intervals // void interrupt() { count = count + 1; } if you don't declare the variable as ...
3,263,924
3,263,947
using System::Drawing namespace in managed C++ class library
I am moving a few functions from a Managed C++ Winforms app to a class library so that I can call them in a new C# app I'm writing. However one of the functions returns a System::Drawing::Bitmap^ and uses the System::Drawing::Color class which is causing an error saying that System does not contain a namespace called D...
You probably need to add a reference to System.Drawing.dll. Right-click your project and choose "Add Reference", it should be there somewhere.
3,264,259
3,264,830
Q_OBJECT linker error!
I am receiving the following linker error when I build my application. HIMyClass.obj:: error: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall CHIMyClass::metaObject(void)const " (?metaObject@CHIMyClass@@UBEPBUQMetaObject@@XZ) File not found : HIMyClass.obj HIMyClass.obj::...
Such errors usually mean that you haven't added the header of your class to "HEADERS" variable in pro file (meta object compiler generates moc_ files only for headers listed in this variable). Remember to run qmake after you change .pro file!
3,264,278
3,264,516
C++ - Superclass constructor producing an instance of a subclass
I have two classes, one of which is a subclass of another, and differs only by the fact that it contains an additional member variable to its parent. I am not using the default constructor, passing in a reference to a single object as the constructors parameter. What I would like is for the constructor of the parent to...
If you're set against a factory class, why not just a static function? class Subclass { public: static Superclass* create(const MyObject* const object) { if (object->createSubclass()) { return new Subclass(object); } else { return new Baseclass(obj...
3,264,294
3,264,866
Netbeans: how to include other c++ static library project?
I am really new to c++ and am using Netbeans for now. I managed to create a Sign.h and Sign.cpp containing a working class Sign. I added these to a Console Project and it works great: #include <iostream> #include <ostream> #include "Sign.h" int main() { Sign sign = Sign::parse("b"); std::cout << ...
You need two files from a library. The library file (.lib on windows, .a on linux) and the include file (.h files). The Options => Build => Linker => Libraries is only for the library file. You also need to set the path for the includes under File => Project Properties => Build => C++ Compiler => General => Include ...
3,264,299
3,264,638
Why do I need std::get_temporary_buffer?
For what purpose I should use std::get_temporary_buffer? Standard says the following: Obtains a pointer to storage sufficient to store up to n adjacent T objects. I thought that the buffer will be allocated on the stack, but that is not true. According to the C++ Standard this buffer is actually not temporary. What a...
Stroustrup says in "The C++ Programming Language" (§19.4.4, SE): The idea is that a system may keep a number of fixed-sized buffers ready for fast allocation so that requesting space for n objects may yield space for more than n. It may also yield less, however, so one way of using get_temporary_buffer() is to optimis...
3,264,420
3,264,447
Lifetime of Qt Objects
What are the lifetimes of Qt Objects? Such as: QTcpSocket *socket=new QTcpSocket(); When socket will be destroyed? Should I use delete socket; Is there any difference with: QTcpSocket socket; I couldn't find deep infromation about this, any comment or link is welcomed.
Qt uses parent-child relationships to manage memory. If you provide the QTcpSocket object with a parent when you create it, the parent will take care of cleaning it up. The parent can be, for example, the GUI window that uses the socket. Once the window dies (i.e. is closed) the socket dies. You can do without the pare...
3,264,597
3,264,631
How can class fields be initialized?
A bit of a basic question, but I'm having difficulty tracking down a definitive answer. Are initializer lists the only way to initialize class fields in C++, apart from assignment in methods? In case I'm using the wrong terminology, here's what I mean: class Test { public: Test(): MyField(47) { } // acceptable ...
In C++x0 the second way should work also. Are initializer lists the only way to initialize class fields in C++? In your case with your compiler: Yes.
3,264,665
3,273,847
C stat() and daylight savings
I'm having serious trouble with the function stat(). I have an application compiled under cygwin ond Windows 7 and the same app compiled with MSVC++ on Windows 7. The app contains the following code: struct stat stb; memset( &stb, 0, sizeof( stb ) ); stat( szPath, &stb ); cout << hex << uppercase << setw(8) << stb.st...
To obtain both reliability and portability here (or in most situations of this sort where two platforms do different things with what should be the "same" code), you will probably need to use some form of target-dependent code, like: #ifdef _MSC_VER // do MSVC++-specific code #else // do Linux/Cygwin/generic code...
3,264,789
3,265,049
How to convert a void* to a type that can be used in C#? Interoperability between C DLL and C#
I am a C/C++ programmer, but I was asked to update a program that was written in C# to communicate with a device. My knowledge of C# is very basic. The previous version was totally written in C#, but now the API that in fact access the device was changed to C. I found out that I can import the C function APIs by using:...
you are passing IntPtr instead of ref IntPtr, the definition should look like this: [DllImport("myapi.dll")] public static extern int myfunct( [MarshalAs(UnmanagedType.LPTStr)] string lpDeviceName, ref IntPtr hpDevice);
3,264,795
3,265,217
How-to override KeyPressEvent for an editable QComboBox?
I have a class named ValidableComboBox that derives directly from QComboBox. Every instance of ValidableComboBox has setEditable() set to true. My goal is to add some signal that will be emitted whenever someone presses return key in the QComboBox. To do so, I reimplemented void KeyPressEvent(QKeyEvent* e) in Validable...
The funktion you've seem to be using in your kode has a Kapital K, instead of a small k, ok? :-D
3,264,803
3,264,977
C++ Pointer data members: Who should delete them?
So say I have a class like this: class A { public: A( SomeHugeClass* huge_object) : m_huge_object(huge_object) {} private: SomeHugeClass* m_huge_object; }; If someone uses the constructor like this: A* foo = new A(new SomeHugeClass()); Who's responsibility is it to call del...
I try to follow this simple rule whenever it is possible: The one who calls new should call delete as well. Otherwise the code soon becomes too messy to keep track of what is deleted and what is not. In your case, if A::A receives the pointer, it must not delete it. Think of this simple case: SomeHugeClass* hugeObj = n...
3,264,862
6,419,549
How can I create a map file with line numbers in Visual C++ 2005?
I can find information to do what I want in VC++ 6.0 at codeproject.com, but the options it suggests (e.g. /mapinfo:lines) are not supported in VC++ 2005.
Unfortunately the answer seems to be simple - you can't in any Visual C++ release after 2003. http://msdn.microsoft.com/en-us/library/bha0yc3d(v=VS.71).aspx shows support for the option. http://msdn.microsoft.com/en-us/library/bha0yc3d(v=VS.80).aspx does not. I had a bit of a search though and found http://www.codeproj...
3,264,863
3,265,149
How to determine method parameter types during runtime in C/C++ under .NET?
in C# it is possible by using reflection to determine parameter types of some method as well as class members (method, properies..). I suppose that this is possible because of IL and .NET technology, right ? If so is it possible to use reflection or some similar technique for C/C++ writen under Visual studio 2005/2008...
It is possible because of metadata in an assembly, put there by the compiler. And an extensive API that allows reading that data. And the essential Object.GetType() method and typeof keyword. None of which is available in a C or C++ compiler. You could hack around this a bit with RTTI and reading the debug symbol fi...
3,265,211
3,265,404
Porting Assembly to C/C++?
I would like to have this x86 ASM code ported to C or C++, as I don't understand ASM =) Searching Google it seams Relogix and IDA Pro can do it. But I don't suppose they are cheap, given I only have this one source. Understanding the math or the algorithm how it works would be just as good, as I am going to use OpenGL ...
In general case, this cannot be done. In this particular case, this cannot be done because this assembly program interacts with PC BIOS directly, using int 10h to turn on 320x200 256 VGA mode, and it interacts with PC hardware directly, by writing to IO ports 0x3c8 and 0x3c9 (this sets the VGA palette) and by reading f...
3,265,479
3,265,572
Header files without .h in C++
I'm having trouble including standard header files like iostream.h and fstream.h. On my system, under usr/include/c++/4.3, none of the files have the ".h" extension (for example, it's just iostream not iostream.h). That would be fine and dandy, but I'm trying to use another library, DCMTK, which does things like #inclu...
I would suggest you to take a look here. It explains why and when this iostream.h / iostream was born, why it exists and how you should solve these issues. Mainly iostream.h is to be considered DEPRECATED UNRELIABLE and IMPLEMENTATION SPECIFIC and using the iostream in place of that one can cause errors..
3,265,592
3,266,790
Python API C++ : "Static variable" for a Type Object
I have a small question about static variable and TypeObjects. I use the API C to wrap a c++ object (let's call it Acpp) that has a static variable called x. Let's call my TypeObject A_Object : typedef struct { PyObject_HEAD Acpp* a; } A_Object; The TypeObject is attached to my python module "myMod" as "A". I have...
Essentially, what you're trying to do is define a "static property". That is, you want a function to be called when you get/set an attribute of the class. With that in mind, you might find this thread interesting. It only talks about Python-level solutions to this problem, not C extension types, but it covers the bas...
3,265,763
3,266,606
C++ fputs Assert on Windows 2008 Server
In the below code the fputs(...) throws an assert when running on Windows Server 2008. I don't have this problem on a Vista or XP machine. I'm at a loss as to what is causing it? The assert is: Stream != NULL It seems to be random too, as sometimes it seems to succeed... as the log files get created. Can anybody hel...
Is it the second fputs that's asserting? Is it possible your vsprintf is overrunning the end of your buffer? Your format string and actual varargs may not match correctly. Your question is tagged C++ and there are definitely better ways to do this in that language. At least consider using std::ofstream to do your writi...
3,265,942
3,265,978
What does this function do?
I am reading a program which contains the following function, which is int f(int n) { int c; for (c=0;n!=0;++c) n=n&(n-1); return c; } I don't quite understand what does this function intend to do?
It counts number of 1's in binary representation of n
3,265,999
3,266,032
Tool for tracing C++ program execution
I recently read in a magazine that there is a new commercial developer tool for Windows which monitors a C++ program's execution and creates traces for visual inspection. I, however, cannot remember the tool's name (it is not Insure++ and also not BugTrapper). In the resulting trace, you see every code line that was vi...
I use GDB and I still love it. Edit: Thanks for @T.E.D, it may be GPROF which report hits count on code line/segment visited.
3,266,019
3,404,206
CoInitializeEx and CoInitializeSecurity failure
I have a C# method that is calling a C++ method. The C++ method uses WMI, so it calls CoInitializeEx(0, COINIT_MULTITHREADED) and then CoInitializeSecurity etc... before making the WMI select. My Problem, CoInitializeEX if failing with code 2147417850 (RPC_E_CHANGED_MODE) I tried to create a new STA thread from c# and...
I removed both calls, problem solved.
3,266,343
3,266,489
C++: Platform dependent types - best pattern
I'm looking for a pattern to organize header files for multiple platforms in C++. I have a wrapper .h file that should compile under both Linux and Win32. Is this the best I can do? // defs.h #if defined(WIN32) #include <win32/defs.h> #elif defined(LINUX) #include <linux/defs.h> #else #error "Unable to determine OS or...
You should use a configuration script able to perform platform checks and generate the appropriate compiler flags and/or configuration header files. There are several tools able to perform this task, like autotools, Scons, or Cmake. In your case, I would recommend using CMake, as it nicely integrates with Windows, bein...
3,266,443
3,266,480
Can you use a shared_ptr for RAII of C-style arrays?
I'm working on a section of code that has many possible failure points which cause it to exit the function early. The libraries I'm interacting with require that C-style arrays be passed to the functions. So, instead of calling delete on the arrays at every exit point, I'm doing this: void SomeFunction(int arrayLengt...
Do not use shared_ptr or scoped_ptr to hold pointers to dynamically allocated arrays. shared_ptr and scoped_ptr use delete ptr; to clean-up when the pointer is no longer referenced/goes out of scope, which invoked undefined behaviour on a dynamically allocated array. Instead, use shared_array or scoped_array, which cor...
3,266,493
3,266,626
C++ container question
I was looking for some suitable 2D element container. What I want is the ability to iterate through every element of the container using, for example BOOST_FOREACH and I also would like to have an ability to construct subview (slices / subranges) of my container and, probably iterate through them too. Right now I am us...
I do the following (array type is container/iterator range concept): ublas::matrix<douple> A; foreach (double & element, A.data()) { } However, this will not work for slices: your best solution is to write an iterator for them. Here is an example of using multi_array to provide storage of a custom class. Perhaps you c...
3,266,580
3,266,612
Extern Struct in C++?
I'm using extern to fetch variables from another class, and it works fine for int's, float's etc... But this doesn't work, and I don't know how to do it: Class1.cpp struct MyStruct { int x; } MyStruct theVar; Class2.cpp extern MyStruct theVar; void test() { int t = theVar.x; } It doesn't work because Class2 doesn...
You put the struct MyStruct type declaration in a .h file and include it in both class1.cpp and class2.cpp. IOW: Myst.h struct MyStruct { int x; }; Class1.cpp #include "Myst.h" MyStruct theVar; Class2.cpp #include "Myst.h" extern struct MyStruct theVar; void test() { int t = theVar.x; }
3,266,679
3,267,301
Initializer list makes variable uninitialized?
I have a class with the only constructor like this: IntroScreen::IntroScreen(Game *game) : View(game), counter(0.0f), message(-1), continueAlpha(255), continueVisible(false), screenAlpha(255), fadeIn(false), fadeOut(false) { } And somewhere in a method I have this if-statement if (counter > 10.0f) And Valgrin...
I found it: getSpeedFactor() returns only the first time I call it a complete wrong number because of time-functions like gettimeofday(). The start value (to time how long it took to update the game) is set initialized to zero and the stop value is micros of the day: which gives a time of the whole day instead of the u...
3,266,886
3,266,899
how to specialize templated member functions of non-templated classes?
suppose I have a file alpha.h: class Alpha { public: template<typename T> void foo(); }; template<> void Alpha::foo<int>() {} template<> void Alpha::foo<float>() {} If I include alpha.h in more than one cpp file and compile with GCC 4.4, it complains there are multiple definitions of foo<int> and foo<float> acros...
use inline keyword template<> inline void Alpha::foo<int>() {} alternatively, provide implementation in separate cpp file
3,266,929
3,267,107
Cast int16_t memory to float
I have a function from an external source that returns an array of 2 uint16_t elements (which I cast to int). I have already been able to cast these to one "big" int ((i1 << 16) + i2) Now I need to be able to cast this to float, keeping the point value as is in memory. Can anyone suggest a way or point me in the right ...
I'd use a union: union fltconv { float f; uint32_t i; } u; u.i = ((uint32_t) i1 << 16) | i2; float f = u.f; It's more explicit about what you're doing. Bear in mind that this is very nonportable.
3,267,152
3,267,220
STL, reducing an array, c++
For a hw assignment, we are to code a reduce routine that looks like: int reduce(long array[], int size) //Where array is the array to reduce, and size is the size of the array. Using STL. My initial thoughts were to create a set, put all items in the set with a comparison, but then I realized that the set I would c...
Sort the array using std::sort, then apply std::unique on it to remove duplicates. std::unique works only on sorted arrays. Just to simplify matters here is how you get begin and end of a native array: long* begin = array; long* end = array + size; Once you have these two things, you can apply standard algorithms ea...
3,267,541
3,267,582
Why does returning shared_ptr<T> as shared_ptr<const T> result in "returning address of temporary" warnings?
class Example { boost::shared_ptr<FilterProvider> filterProvider; public: void RegisterFilter(const boost::shared_ptr<FilterProvider>& toRegister) { filterProvider = toRegister; } const boost::shared_ptr<const FilterProvider>& GetFilter() const { return filterProvider; // Compile...
Your shared ptr is declared with type boost::shared_ptr<FilterProvider> You are returning boost::shared_ptr<const FilterProvider> by const reference. See the difference? The types are not the same, but the former is convertible to the latter, and the compiler invokes the conversion. The result of the conversion is ...
3,267,559
3,267,985
Why doesn't my visual studio 2k8 C++ project work with unicode characters?
I am trying to get unicode working on windows in a visual studio 2k8 project, and I am not sure why I can't get my project to work. My machine has all the Eastern language support installed. I went to properties->project defaults->character set: and it is set to "Use Unicode Character Set". Here is my test code: #inclu...
The problem is not completely because of your code, it is how you look at the text. The only way that your text editor can know that the file contains Unicode is by the required BOM. You didn't write one. Use "ccs=UTF-16LE" in the _wfopen() mode string. There's a similar problem with the console, it cannot display U...
3,267,685
3,268,804
how to make sure not to read a file before finishing the write to it
When trying to monitor a directory using inotify on Linux, as we know, we get notified as soon as the file gets created (before the other process finish writing to it) Is there an effective way to make sure that the file is not read before writing to it is complete by the other process? We could potentially add a delay...
Based on your question, it sounds like you're currently monitoring the directory with the IN_CREATE (and maybe IN_OPEN) flag. Why not also use the IN_CLOSE flag so that you get notified when the file is closed? From there, it should be easy to keep track of whether something has the file open and you'll know that you...
3,267,738
3,292,220
Compile error with embedded assembler
I don't understand why this code #include <iostream> using namespace std; int main(){ int result=0; _asm{ mov eax,3; MUL eax,3; mov result,eax; } cout<<result<<endl; return 0; } shows the following error. 1>c:\users\david\documents\visual studio 2010\projects\assembler_in...
Use: imul eax, 3; or: imul eax, eax, 3; That way you don't need to worry about edx -register being clobbered. It's "signed integer multiply". You seem to have 'int' -result so it shouldn't matter whether you use mul or imul. Sometimes I've gotten errors from not having edx register zeroed when dividing or multiplying...
3,268,067
3,268,121
Newbie design considerations for a C/C++ application
I'm quite new to programming "larger" applications. I have now written a command line application with a few thousand lines of code in Visual C++ 2010, which compiles and works fine. Most of the code is C-compliant (I think), however, I found it useful to use some C++ constructs here and there. E.g., sometimes I used n...
IMO, there is no need to be "C" compliant in 2010. Just use C++ and all its advantages (STL, boost, all that jazz... ) AFAIK, putting the code in header files is not normal practice, usually code goes in implementation files ( .c, .cpp, ... ). Putting code in C/CPP files ( instead of header files) will let you optimiz...
3,268,073
3,268,185
QObject: Cannot create children for a parent that is in a different thread
I am using Qt 4.6.0 (32 bit) under Windows 7 Ultimate. Consider the following QThread: Interface class ResultThread : public QThread { Q_OBJECT QString _post_data; QNetworkAccessManager _net_acc_mgr; signals: void onFinished(QNetworkReply* net_reply); private slots: void onReplyFinished(QNetworkReply...
The run() member function is executed in a different thread, rather than the thread where QNetworkRequestManager object was created. This kind of different-thread problems happen all the time with Qt when you use multiple threads. The canonical way to solve this problem is to use signals and slots. Create a slot in the...
3,268,097
3,268,148
Approximate a R2 line by a set of points
I'm working on an application with statistic analysis, and I need some help. Given a set of n points, how can I approximate a line by them. I'm sure there is an algorithm but I couldn't find it. Thanks!
The topic is called linear regression, or ordinary least squares. You should be able to find more details in any linear algebra or stat book. A Java implementation can be found here
3,268,117
3,268,135
Setting a custom allocator for strings
I know I can set a custom allocator for vectors using the syntax vector<T, Alloc>. Is there a way I can do the same for strings?
Yes. All string classes come from the class template basic_string, declared as such: template <class charT, class traits = char_traits<charT>, class Allocator = allocator<charT> > class basic_string; For example, std::string is just typedef basic_string<char> string;. The third template parameter is the al...
3,268,139
3,455,378
Filtering Memory Leaks dumped by _CrtDumpMemoryLeaks
I am trying to find leaks in my program, which is a framework based on Ogre3D. I am using the following defines in my code to 'new' anything so that later on any leak can be detected and reported correctly by the program. #ifdef _DEBUG #include <crtdbg.h> #define MyFW_NEW new(_NORMAL_BLOCK ,__FILE__, __LINE__) ...
There is no solution to this problem that I could find. If somebody does find the solution, I will change the answer to theirs, otherwise the answer is, don't waste your time, find a good leak detector :)
3,268,230
3,268,306
How can we properly implement Python bindings of subclassed C++ objects?
I'm having an issue with a rather intricate interaction of C++ and Python that I'm hoping the community can help me with. If my explanation doesn't make sense, let me know in the comments and I'll try to clarify. Our C++ code base contains a parent classes called "IODevice" which is a parent to other classes such as "...
Are your types FilePy and IODevice derived from PyObject? Otherwise, the C++ compiler will interpret: inputFile = (IODevice*) cD_py; as: inputFile = reinterpret_cast<IODevice*> (cD_py); rather than what you expected: inputFile = dynamic_cast<IODevice*> (cD_py); If the actual type passed is not PyObject, or IODevice...
3,268,252
3,268,328
Strange compiler errors with code::blocks
I switched from Visual Studio to Code::Blocks yesterday, and just had some strange compiler error messages. I included windows.h and i can use all the API calls just fine, such as creating window classes and creating windows / buttons and stuff. But when I tried to send some keypresses with SendInput(), I got error mes...
I think you need the pre-processor directives (Visual Studio may already add them): What do you have _WIN32_WINNT defined as? Perhaps you could add: #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif or you can add it to your pre-processor directives as part of your compile sequence. Any good compiler will have i...
3,268,627
3,268,732
VariantClear() throws an exception when called on A VARIANT containing a SAFEARRAY
I am trying to wrap up some data from an array of BYTES into a VARIANT but I can't seem to free the data: When I run this code... SAFEARRAY * NewSArray; SAFEARRAYBOUND aDim[1]; // a one dimensional array aDim[0].lLbound = 0; //Sets the index to start from 0 //Sets the number of elements (bytes) that will go into the ...
SafeArrayCreate creates a safe-array and allocates memory for the pvData member. You should not reset the pvData member after this. You should copy your data from pBuffer into what pvData points to, or use the SafeArrayAccessData or SafeArrayPutElement functions.
3,268,682
3,268,867
How to interface with an executable in C++
I have an executable that I need to run some tests on in C++ - and the testing is going to take place on all of Windows, Linux and Mac OSes. I was hoping for input on: How would I interface with the previously built executable from my code? Is there some kind of command functionality that I can use? Also, since I thi...
As I understand, you want to: Spawn a new process with arguments not known at runtime. Retrieve the information printed to stdout by the new process. Libraries such as QProcess can spawn processes, however, I would recommend doing it by hand for both Windows and MacOS/Linux as using QProcess for this case is probably...
3,268,801
3,271,456
How do you 'de-serialize' a derived class from serialized data?
How do you 'de-serialize' a derived class from serialized data? Or maybe I should say, is there a better way to 'de-serialize' data into derived classes? For example, suppose you had a pure virtual base class (B) that is inherited by three other classes, X, Y and Z. Moreover, we have a method, serialize(), that will tr...
In fact, it's a more general issue than serialization called Virtual Constructor. The traditional approach is to a Factory, which based on an ID returns the right derived type. There are two solutions: the switch method as you noticed, though you need to allocate on the heap the prototype method The prototype method ...
3,268,890
3,269,048
How to make a void** point to a function?
I have code that looks like this: extern "C" __declspec(dllexport) myInterface(int id, void** pFunction) { ... } I need to make the void** pFunction argument point to a function so that the caller can use this function via the pFunction pointer. This function gets called through a DLL, I don't want to do it this w...
As Jonathan Leffler and David Thornley mentioned, you aren't guaranteed that a function pointer can be converted to void* and back. A portable workaround would be to package the function pointer into a struct and to pass a pointer to that. (Be aware that void** itself might have its own issues. You can avoid this too...
3,268,990
3,269,017
File/folder layout for a large C++ project with multiple levels of inheritance
I'm in the planning stage of a relatively large (10k+ lines) project with several classes (30+) and several levels of class inheritance (5+). What is the best (or most conventional) way to lay out my project in terms of file and folder structure? Should I have one file per class? Should I have one folder per inheritan...
1) Yes. One file per class in most cases is a good idea. Unless you have a really trivial class, or a collection of abstract interfaces, use one class per file. 2) Try to separate things. Usually in a project that big, you'll have some code that are specific to some parts, others that are common to many parts. Those...
3,269,016
3,269,036
Linker Error when separating code into .h and .cpp files
I have an implementation for printing out enum values in c++ If I put all the code in a .h file, everything works nicely. If I separate out the function implementation into .cpp files, I get a linker error. Here is my main file #include <iostream> #include <vector> #include "Day.h" using namespace std; int main(){ ...
You are initializing two copies of vector<string> DayNames = vector<string>(); because you included the header twice. You should replace it with extern vector<string> DayNames; in the h file and vector<string> DayNames = vector<string>(); in the cpp file. Also you seem to have two copies of ostream & operator<<(o...
3,269,091
3,269,236
Help with connected outlines
I'm making a vector drawing application. I use this algorithm to generate outlines. This algorthm works well, except it does not close the outline as seen here: alt text http://img716.imageshack.us/img716/2633/noclosure.png I'm not sure what I should do to ensure that it always closes the outline. I tried inserting the...
Try appending a copy of the first and second points to the end of the vector before plotting it. Your first and last line segment will overlap, but it should ensure that all the points are connected and all corners are rounded similarly.
3,269,212
3,336,051
Non-Rigid Body 2D Physics Engines in C++
I'm trying to experiment with 2D physics engines in C++. So far, it seems the most popular is Box2D. Unfortunately, Box2D is a rigid body physics engine and that's not really going to help me with what I want to try. I want to be able to define a shape which has a number of vertices joined by springs, such that when th...
There are several packages/engines out there that support deformable/soft bodies. If you want something free you can for example check out Phyz, SOFA or Bullet. There is a detailed listing on wikipedia. Most of these are 3D-based but you can adapt them to a 2D model by setting up the scene as a plane. Happy coding!
3,269,226
3,269,250
RegQueryValueEx gets a weird value
I am trying to retrieve some values from the registry. Here is the full path: [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes] "ThemeChangesMousePointers"=0x00000001 (1) And here is my code: HKEY hKey; DWORD dwDisp = REG_DWORD; DWORD dwType; DWORD dwSize = sizeof(DWORD); DWORD dwValue = 0; DWORD dwR...
RegQueryValueEx does not call SetLastError, it returns it's error code directly. Return Value If the function succeeds, the return value is ERROR_SUCCESS. If the function fails, the return value is a system error code. If the lpData buffer is too small to receive the data, the function returns ERROR_MORE_DATA. If the ...
3,269,256
3,269,366
Simple questions about cin/cout overloading
I know this is pretty basic but I've kind of been guessing up to this point. Foo is just an object with private inheritance from the string class which is why I cast it. Using examples from Primer C++ (Prata's) So if I have a function like: istream & operator>>(istream & is, Foo & f) { is >> (string &)f; re...
It becomes very easy if you replace the overloaded operators with normal function calls. cin >> f simply translates to: operator >>(cin, f); Now think of cin >> f >> x as (cin >> f) >> x. This translates to: operator >>(operator >>(cin, f), x); Since the first operator returns cin, during execution, this actually bec...
3,269,390
3,269,432
How to get hWnd of window opened by ShellExecuteEx.. hProcess?
This "simple" issue seems to be fraught with side issues. eg. Does the new process open multiple windows; Does it have a splash screen? Is there a simple way? (I'm starting a new instance of Notepad++) ... std::tstring tstrNotepad_exe = tstrProgramFiles + _T("\\Notepad++\\notepad++.exe"); SHELLEXECUTEINFO SEI={0...
First use WaitForInputIdle to pause your program until the application has started and is waiting for user input (the main window should have been created by then), then use EnumWindows and GetWindowThreadProcessId to determine which windows in the system belong to the created process. For example: struct ProcessWindow...
3,269,469
4,860,335
What types of abstract interfaces are most common in practice
I wasn't completely sure how to phrase what I wanted to ask in the title so I'll try to clarify it better in what follows. For C++ software library developers, what abstract interfaces do you find yourselves rewriting often between projects/jobs? For instance, I would imagine that it is fairly common practice for diff...
it depends on what you're developing in some cases. here's a short list: clone, create (factory method), serialization, threading, mediation, observing.
3,269,478
3,269,487
What is bool in C++?
I ran across some very interesting code that makes me wonder about what bool is. I've always considered it to be a primitive type, like int or char or long. But today, I saw something that looked like this: void boolPtrTest() { bool thisBool = true; boolPtrHere(thisBool); printf("thisBool is %s\n", thisBo...
void boolPtrHere(bool& theBool) { theBool = false; // uhh, dereferencing anyone? } There is nothing wrong with this code. The bool is taken by reference. No dereferencing is required. bool myBool = new bool(); new returns an address, which is converted to true, since it never returns a nonzero value. This is a co...
3,269,529
3,269,546
I don't understand this Huffman algorithm implementation
template<class T> void huffman(MinHeap<TreeNode<T>*> heap, int n) { for(int i=0;i<n-1;i++) { TreeNode<T> *first = heap.pop(); TreeNode<T> *second = heap.pop(); TreeNode<T> *bt = new BinaryTreeNode<T>(first, second, first.data, second.data); heap.push(bt); } ...
The heap's tree structure does not necessarily match the resulting Huffman tree -- rather, the heap contains a forest of partial Huffman trees, initially each consisting of a single symbol node. The loop then repeatedly takes the two nodes with the least weight, combines them into one node, and puts the resulting comb...
3,269,575
3,286,046
How do I add a custom build target to a Visual C++ 2010 project?
There are plenty of guides out there which help you mimic VS2008's "Custom Build Step" in VS2010 with MSBuild. However, I'd like my build to be smarter and make use of MSBuild. I've written a little MSBuild task which invokes the ANTLR parser generator. That build task works flawlessly when I run it in a simple test MS...
Before reading this answer, you'll probably want to see: General .vcxproj File Reference The New Way of doing Build Extensibility in .NET 4 The old way of extending MSBuild, and the one mentioned by the reference book I have, essentially is based on overriding default-empty targets supplied by Microsoft. The new way,...
3,269,614
3,272,470
ffmpeg encoding sample wanted?
I found this tutorial about ffmpeg the thing i do not get is how to encode video. can any one, please provide a tutorial.. with explanations for that? (not that i dont get this official one but i'd love to see more comments)
FFmpeg's developers guide refers to an api sample featuring encoding and decoding of both audio and video. This answer links to it as well.
3,269,627
3,269,645
c++: local array definition versus a malloc call
What is the difference between this: somefunction() { ... char *output; output = (char *) malloc((len * 2) + 1); ... } and this: somefunction() { ... char output[(len * 2) + 1]; ... } When is one more appropriate than the other? thanks all for your answers. here is...
Use locals when you only have a small amount of data, and you are not going to use the data outside the scope of the function you've declared it in. If you're going to pass the data around, use malloc. Local variables are held on the stack, which is much more size limited than the heap, where arrays allocated with mall...
3,269,767
3,269,780
how to output an int in binary?
int x = 5; cout<<(char)x; the code above outputs an int x in raw binary, but only 1 byte. what I need it to do is output the x as 4-bytes in binary, because in my code, x can be anywhere between 0 and 2^32-1, since cout<<(int)x; doesn't do the trick, how would I do it?
You can use the std::ostream::write() member function: std::cout.write(reinterpret_cast<const char*>(&x), sizeof x); Note that you would usually want to do this with a stream that has been opened in binary mode.
3,269,809
3,269,834
Why is std::vector::operator[] 5 to 10 times faster than std::vector::at()?
During program optimization, trying to optimize a loop that iterates through a vector, I found the following fact: ::std::vector::at() is EXTREMELY slower than operator[] ! The operator[] is 5 to 10 times faster than at(), both in release & debug builds (VS2008 x86). Reading a bit on the web got me to realize that at()...
The reason is that an unchecked access can probably be done with a single processor instruction. A checked access will also have to load the size from memory, compare it with the index, and (assuming it's in range) skip over a conditional branch to the error handler. There may be more faffing around to handle the poss...
3,270,125
3,270,144
How do vector applications skew polygons?
I know how to move, rotate, and scale, but how does skewing work? what would I have to do to a set of verticies to skew them? Thanks
Offset X values by an amount that varies linearly with the Y value (or vice versa). Edit: Doing this with a rectangle: Let's say you start with a rectangle (0, 0), (4, 0), (4, 4), (0, 4). Let's assume you want to skew it with a slope of 2, so as it goes two units up, it'll move one to the right, something like this (ha...
3,270,361
3,270,804
Distorting a polygon (Like Photoshop's distort) (Perspective Transformation)
In Photoshop there is a tool that allows the selection to be "Distorted". This allows easy shadow creation among other things. How could this sort of distortion be applied for a polygon (a bunch of points)? Thanks
If your aim is to accomplish something like this (black original, red after distortion) then you can: fix a base for applying distortion (generally normal to the direction in which you want to distort, for example - here the direction of distortion is towards the right and the base is the bottom edge of the rectangle...
3,270,427
3,270,519
When is memory allotted to static variables in C++
I am a newbie to C++ and facing a problem. I read in a book that memory is allotted to a static variable, once the object is created of that class. Now, what if I make this static variable global ? When would be it initialized in that case ? Plus, I have also read in some articles that static variables are allotted on ...
First: STOP THINKING ABOUT GLOBAL VARIABLES IN C AND C++, or you will perpetuate your state of confusion. The issue is more complex than in, e.g., Python or Pascal, and therefore you can't just use a single word for the concept(s). Second, there is no "heap" or "stack" -- these are operating system and CPU details, and...
3,270,437
3,270,448
What are these windows? .. "M" and "Default IME" (from GetWindowText)
Using EnumWindows and GetWindowText, I see many titles with "M' and "Default IME". What is their primary function?.. It seems to be something quite fundamental.
I'm not sure about the "M" one, but the "Default IME" window is created by the default Input Method Editor (IME). An IME allows the user to enter characters in a script that may involve a number of separate keystrokes, e.g. Chinese or Korean. Different IMEs can be installed via the Region and Language dialogs in Contro...
3,270,757
3,270,986
In resources of a executable file, how does one find the default icon?
i need to find the default icon of a windows executable (PE file = dll, exe, com..) programatically. I do know how to walk throught the resources and identify what is an icon, what a cursor etc, but as far as i know none of the icons is in any way marked as the default one. So, does somebody know, how to find the defau...
After a lot of searching, i found out that the default icon is not the one with the lowest id. Windows use several sizes of one icon for various things. For more information, look here, but in short here is the important information: When the system displays an icon, it must extract the appropriate icon image from the...
3,270,917
3,275,101
which kinds of constructors may be applied during compile time as optimization, for objects with static storage duration?
take two following classes and their constructors as samples: class One{ public: One(int a,int b):adad1(a),adad2(b){} private: int adad1; int adad2; }; class Two{ public: Two(int input[]){ for (int i=0;i<10;i++) araye[i]=input[i]; } private: int araye[10]; }; considering objects with static stor...
There is no guarantee that any of the two are statically initialized before any runtime code is executed. For the first, it's easy to make it happen, though class One{ public: int adad1; int adad2; }; // initialized statically, if a and b are constant-expressions One one = { a, b }; As another guy says, constex...
3,270,967
3,271,018
How to send float over serial
What's the best way to send float, double, and int16 over serial on Arduino? The Serial.print() only sends values as ASCII encoded. But I want to send the values as bytes. Serial.write() accepts byte and bytearrays, but what's the best way to convert the values to bytes? I tried to cast an int16 to an byte*, without...
Yes, to send these numbers you have to first convert them to ASCII strings. If you are working with C, sprintf() is, IMO, the handiest way to do this conversion: [Added later: AAAGHH! I forgot that for ints/longs, the function's input argument wants to be unsigned. Likewise for the format string handed to sprintf(). So...
3,271,048
3,271,252
How to create a comparator with Boost?
I'm new to Boost, but not to functional programming, and I'm trying to see where Boost can help me out. I have a list of 2D points, and I want to extract the minimum x coordinate. The Point class has a member function float x() const so I can use boost::mem_fn as follows: boost::mem_fn(&Point::x) But in order to use s...
I'm not aware of any boost construct similar to your Compare_by. However, boost::bind can do the trick. Point leftmostPoint = *std::min_element(points.begin(), points.end(), boost::bind(std::less<Point::type_x>(), boost::bind( &Point::x, _1 ), boost::bind( &Point::x, _2 ))); Yeah, that's not pretty :/ Lucki...
3,271,065
3,271,085
friend with class but can't access private members
Friend functions should be able to access a class private members right? So what have I done wrong here? I've included my .h file with the operator<< I intent to befriend with the class. #include <iostream> using namespace std; class fun { private: int a; int b; int c; public: fun(int a, int b); ...
In here... ostream& operator<<(ostream& out, fun& fun) { out << "a= " << fun.a << ", b= " << fun.b << std::endl; return out; } you need ostream& operator<<(ostream& out, const fun& fun) { out << "a= " << fun.a << ", b= " << fun.b << std::endl; return out; } (I've been bitten on the bum by this numer...
3,271,189
3,271,203
Blitting zoomed images using SDL
Is there any way to Blit a zoomed (in) version of a certain image/sprite using SDL? (Besides manually saving a zoomed version of the image..) Thanks :-)
Not with the SDL API itself. I think there exist libraries (for SDL) who support zooming (so called resizing). EDIT: http://www.ferzkopp.net/joomla/content/view/19/14/
3,271,518
3,271,535
question about bitset in c++
i have tried to implement following code #include <iostream> #include <bitset> using namespace std; int main(){ //bitset<4>mybits; //cout<<mybits<<endl; int a[]={3,1,4,5,7,8}; int max=a[0]; int t=sizeof(a)/sizeof(a[0]); for (int i=1;i<t;i++){ if (a[i]>max){ max...
The problem: the size of a C++ bitset has to be known at compile-time, and therefore the size is the template parameter to the bitset. A possible solution (and probably better than using a std::vector<bool>, as suggested by other posters): if you wanted to use a bitset whose size you can fix at runtime, you can use dy...
3,271,555
3,272,056
CreatePipe and necessary permissions in C#
I'm trying to add a Sokoban solver (written in C++) to my program in C# (I have got a class in my program that handles marshalling of C++ interface). My program loads solver.dll library which loads solver.exe. Solver.dll and Solver.exe communicate via pipes. The problem is that when I run my program in Visual Studio (d...
Yuck, that's fugly. This can only work well if MyProgram.exe is a console mode application. Required to get input/output redirection working. It probably works in the debugger because of the Visual Studio hosting process. P/Invoking AllocConsole in your program would solve the issue. I'll guess you don't particular...
3,271,585
3,271,638
How much is memory usage likely to grow when moving to 64bit?
When moving an application from 32bit to 64bit, where will increased memory usage occur? I understand that pointers will double in size, I suspect that the chars in a string are 'bunched' to use memory more efficiently (so will not use much more memory). Where else would memory usage increase? Is there anywhere that it...
You may see additional alignment to cost a few extra bytes here and there. Code will probably be larger due to 64 bit constants in operands. As for speed, you may experience slowdowns due to the increased memory usage. The CPU cache will fill up more quickly. I have seen significant speed benefits going from x86 going ...
3,271,631
3,271,850
C++ Sandboxing dynamic libraries
I'm wondering if at all it is possible to sandbox a dynamically linked library via dlopen and friends. The aim is to recover from an error within the library without tearing down the whole application e.g SEGFAULT, etc. Anyone had any experience in this area?
OK well generally speaking exception handling is highly operating system dependent. I am going to make some assumptions and try to provide some generic guidance. Please know that this is by no means an exhaustive reply, but should serve as a place to start. I will assume that: For the most part, you are interested i...
3,271,780
3,290,476
What is C# for C " FILE *f;"?
I am a beginner in C# I wonder how to write in C# C's static void example(const char *filename) { FILE *f; outbuf_size = 10000; outbuf = malloc(outbuf_size); f = fopen(filename, "wb"); if (!f) { fprintf(stderr, "could not open %s\n", filename); exit(1); } fwrite(outbuf, 1, outbuf_size, f); f...
Well, since the sample code of the library you provided reads and writes binary files, I'd suggest System.IO.BinaryReader and System.IO.BinaryWriter. static void example(string filename) { StreamReader sr; BinaryWriter bw; try { sr = new StreamReader(filename); ...
3,272,180
3,272,257
implement stack in c++
How can I code a stack in C++? I have tried this myself as follows: #include <iostream> using namespace std; #define max 10 class stack{ private: int arr[max]; int top; public: stack(){ top=-1;//empty initialy stack } void push(int i){ top++; if (top<max){ ...
The code will be less error prone, and clearer to read, if you only change state (variables, members etc) when you need to. So, if you rewrite the push function into void push(int i){ if (top<max-1){ arr[++top]=i; } else{ cout<<"stack full"<<endl; } } it'll be cleaner. Also, const...
3,272,258
3,272,283
Two short questions about std::vector
When a vector is created it has a default allocation size (probably this is not the right term to use, maybe step size?). When the number of elements reaches this size, the vector is resized. Is this size compiler specific? Can I control it? Is this a good idea? Do repeated calls to vector::size() recount the number o...
In most cases, you should leave the allocation alone unless you know the number of items ahead of time, so you can reserve the correct amount of space. At least in every case of which I'm aware, std::vector::size() just returns a stored value, so it has constant complexity. In theory, the C++ standard allows it to do o...
3,272,341
3,272,365
How to call constructor of objects contained in a std::vector?
When I create a std::vector of objects, the constructor of these objects is not always called. #include <iostream> #include <vector> using namespace std; struct C { int id; static int n; C() { id = n++; } // not called // C() { id = 3; } // ok, called }; int C::n = 0; int main() { vector<C> ...
The reason is that vector::resize inserts copies by calling the automatically provided copy constructor, rather than the constructors you have defined in your example. In order to get the output you want, you can define the copy constructor explicitly: struct C { //.... C(const C& other) { id = n++; // copy oth...
3,272,569
3,272,579
Expression intermediates in GCC (if that's what they're actually called)
I am trying to convert a math library written with VS so it will compile though GCC. The trouble is, I have a lot of overloaded operators that look like this: template<typename T> inline quaternion<T> operator+(quaternion<T> &a, quaternion<T> &b) {return quaternion<T>(a.x+b.x,a.y+b.y,a.z+b.z,a.w+b.w);} and so on. The ...
Your non-modifying operators need to take their arguments by const reference, e.g. template<typename T> inline quaternion<T> operator+(const quaternion<T> &a, const quaternion<T> &b) {return quaternion<T>(a.x+b.x,a.y+b.y,a.z+b.z,a.w+b.w);} Standard C++ does not allow you to bind unnamed temporaries (which your interm...
3,272,599
3,302,780
Can you turn off (specific) compiler warnings for any header included from a specific location?
I've got a third-party library that generates a ton of warnings, even under /W3. Is there a way for me to tell the compiler, "disable C4244 for any file included from this directory, or its subdirectories"? Of course, I don't want to disable the warning in our own codebase, nor do I want to have to track down every p...
I hate to answer my own question here, but I'm afraid that the "correct" answer in this case is: it's not possible.
3,272,600
3,272,636
How to solve a template issue to save different data types to file?
I came a across a new problem when using templates. This is me being a little creative from a book I recently read, expanding his ideas, and it has this code example. Say you have a templated Array2D class. And you have this method (Array2D::WriteFile): bool WriteFile( const char* p_filename ) { FILE* outfile =...
Your objects need to be serializable. Think about what actually happens under the hood when you try to write out the head of a linked list this way - of course it just writes the first node; the write function has no idea what it's writing, so it has no idea how to follow the pointers to the next node and write that to...