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
5,741,686
5,741,733
Having stringstream with some data how to gzip it cross platform way?
So we have some stringstream with somedata. With help of which cross platform library we can turn its contents into gziped format (you would save it into file with extention .tar.gz) Lets get into code: so I have: stringstream body; body << std::ifstream( path.string().c_str(), ios::binary).rdbuf(...
boost.iostreams has optional built-in support for bzip2 and gzip compression/decompression.
5,741,735
5,741,749
C++ std::map s as arguments
Is it possible for me to take an argument of any type of std::map? void myFunction(const std::map<std::string,[INSERT_ANY_CLASS]>& tMap);
Yes, you can make it a function template: template<class T> void myFunction(const std::map<std::string,T>& tMap);
5,741,961
5,742,593
Error while opening a file inside a dll
I am opening a file inside a dll code. I am using fopen. The pointer returned by fopen is NULL. What am I doing wrong? pFile = fopen("C:\\Users\\bruce\\Desktop\\log.txt","w"); I run the code with the debugger. The file gets created but the pointer returned by fopen is NULL which throws an exception when I use fprintf...
After fopen() fails, the error result is stored in the errno global variable (be sure to #include <errno.h>). The strerror() function can convert the errno number into a human readable string.
5,741,970
5,742,985
Registering types from a boost mpl vector
std::string a= "a"; std::string b= "b"; std::string c= "c"; typedef mpl::vector<EasyFixEngineA,EasyFixEngineB,EasyFixEngineC> vecType; RegisterInFactory<EasyFixEngine, mpl::at_c<vecType,0>::type> registerA( a); RegisterInFactory<EasyFixEngine, mpl::at_c<vecType,1>::type,> registerB( b); RegisterInFactory<Easy...
One possibility utilizing mpl::for_each: #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> struct EasyFixEngineA { static const char* const name() { return "a"; } }; struct EasyFixEngineB { static const char* const name() { return "b"; } }; struct Registrator { template<class T> void operator()(T ...
5,742,018
5,755,119
Encrypting ODBC DSN login password programmatically
I am using file DSN for connecting to Sybase database. Login password is encrypted and is stored with EncryptedPassword keyword in the .dsn file. I have the requirement to change the database password and update the DSN accordingly. I am using SQLDriverConnect to connect to the database and SQLWriteFileDSN to modify t...
Take a look at the dbdsn utility that is shipped with SQL Anywhere. If you use the -pe switch, the password you specify will be encrypted when the DSN is saved.
5,742,032
5,742,105
Error subtracting floating point numbers when passing through 0.0
The following program: #include <stdio.h> int main() { double val = 1.0; int i; for (i = 0; i < 10; i++) { val -= 0.2; printf("%g %s\n", val, (val == 0.0 ? "zero" : "non-zero")); } return 0; } Produces this output: 0.8 non-zero 0.6 non-zero 0.4 non-zero 0.2 non-zero 5.55112e-...
Its because floating points numbers can not be stored in memory in exact value. So it is never safe to use == in floating point values. Using double will increase the precision, but again that will not be exact. The correct way to compare a floating point value is to do something like this: val == target; // not saf...
5,742,041
5,745,558
Some of QT examples are not working
After building QT via my Visual Studio 2010 as described here I find out that most part of demos doesn't work. When I open qtdemo.exe and try to Launch some of them (for example Demonstrations->Browser, Demonstrations->Media Player, Qt Declarative Examples->TV Tennis, ...) the same error message "Could not launch the e...
If you followed these configure flags from here, then obviously not all examples will work. These are the ones for a minimalistic Qt build: configure.exe -release -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools -no-qt3support -no-multimedia -no-ltcg If you want all example to work (except webkit), ...
5,742,171
5,742,223
Enforcing Correct Virtual Function Definitions in Derived Classes
Possible Duplicate: Making sure the method declaration is inherited Hello, I have difficulty from time to time enforcing the appropriate definitions of virtual member functions in my class hierarchies. If I mis-define a virtual function inheriting from an interface the bug will quickly come to light as I typically c...
You want to use the override keyword: class Base { virtual void MyFunction() { /*Blah*/ } }; class Child : Base { virtual void MyFunction() override { /* DoSomething*/ } }; If you change the definition of Base::MyFunction you will now get a compile error. override documentation
5,742,531
5,742,851
Member function templates cannot be declared virtual - From Addison Wesley: C++ Templates
From Addison Wesley: C++ Templates Member function templates cannot be declared virtual. This constraint is imposed because the usual implementation of the virtual function call mechanism uses a fixed-size table with one entry per virtual function. However, the number of instantiations of a member functi...
Consider: struct X { template <typename T> T incr(const T& t) { return t + 1; } }; As incr() is applied to different T types, new functions are generated. Say inside app.c++ you have: X x; x.incr(7); // incr<int>() x.incr(7.0); // incr<double>() x.incr("hello"); // incr<const char...
5,742,597
5,742,782
EASTL versus STL, how can there be such a performance difference in std::vector<uint64_t>::operator[]
According to http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html vector<uint64>::operator[] is between 2% and 70% faster in EASTL than a "commonly used commercial version of STL". Unless the commercial version of STL uses range checking, which would make the comparison unfair, how can it possibly be such...
The document states that they used VC++ 2005 for Windows testing, with which checked iterators are enabled by default (yes, even for release builds; same goes for VC++ 2008). I suspect that the performance of operator[] wouldn't be any different if they added -D_SECURE_SCL=0 to their build command-line.
5,742,654
5,742,750
How to aliase a function with variable number of arguments?
I have a method in a class with this signature: void addMessage_( std::string appender, LogLevel level /*= LOGLEVEL_INFO*/, char* msg, ... ); I want to create 'alias' of this method in this way: void debugMsg( std::string appender, char* msg, ... ){ addMessage(appender, LOGLEVEL_DEBUG, msg, ...); } My question is...
It's not possible that way (without macros), you must change your original function to take a va_list. It is fully explained here: Passing variable number of arguments around
5,743,013
5,743,122
exception handling a constructor
This was an interview question of me. Surprisingly i never thought of this kinda question to myself. can we have exception handling inside a constructor c++? in tense and not thinking much i said "yes we could probably do it in a constructor.lets say we are allocating some memory using new operator to a pointer member ...
See this GOTW Constructor Failures question which addresses your query somewhat and goes on to say it is a waste of time.
5,743,079
5,743,405
Accessing environment variable in a fastcgi application
I have writen a fastcGI application using C and C++ I have a free function that returns a string, if a specific environment variable has not been set. The function looks like this: namespace { std::string getNameString() { char * datastr_ = getenv(MY_ENVAR.c_str()); if (datastr_) re...
I suspect that fastcgi processes are spawned in a "cleaned" environment by default, given your observations. Apache certainly provides a way of setting environment variables for fastcgi. This has the added bonus of being slightly less cryptic too (who expects a webservice to behave differently when /etc/environment is ...
5,743,545
44,883,472
What is the fastest way to change a key of an element inside std::map
I understand the reasons why one can't just do this (rebalancing and stuff): iterator i = m.find(33); if (i != m.end()) i->first = 22; But so far the only way (I know about) to change the key is to remove the node from the tree alltogether and then insert the value back with a different key: iterator i = m.find(33)...
In C++17, the new map::extract function lets you change the key. Example: std::map<int, std::string> m{ {10, "potato"}, {1, "banana"} }; auto nodeHandler = m.extract(10); nodeHandler.key() = 2; m.insert(std::move(nodeHandler)); // { { 1, "banana" }, { 2, "potato" } }
5,743,653
5,743,687
Changes to a container while BOOST_FOREACH is iterating through it?
What would happen if a container that BOOST_FOREACH is iterating through is changed inside the BOOST_FOREACH scope? Does BOOST_FOREACH "freeze" the initial state?
In this case behavior is undefined. Look at Hoisting and Iterator Invalidation in official documentation of BOOST_FOREACH.
5,743,678
5,743,699
Generate Random number between 0 and 10
How can i generate Random numbers between 0 and 10? Can I have a sample for this random number generation?
/* rand example: guess the number */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main () { int iSecret, iGuess; /* initialize random seed: */ srand ( time(NULL) ); /* generate secret number: */ iSecret = rand() % 10 + 1; do { printf ...
5,743,704
5,743,792
C++ Function Pointer
Is this possible? If so, I can't seem to get the syntax right. (C++ function pointer) bit of background. The code below has been shorten for this post. The reason for this implementation is to avoid an endless list of SWITCH/CASE or IF/ELSEIF statements; and have an endless list of DECODER_FUNCTION_TABLE (see below...
You call a member function pointer (that's what it's called) with (this->*DECODER_FUNCTION_TABLE[i].pFn)(A); Could put parens around DECODER_FUNCTION_TABLE[i].pFn, but the member access operator . has a higher precedence than member function operator ->*.
5,743,742
5,743,865
which language will be suitable for an web Interface
I am planning to write a webcrawler in c++ and i need to manage the crawler settings in a web interface ...so i am planning to use some languages like perl or python to use as web interface and c++ as language..which will be the best language for c++ to interact with python or perl ..etc..
You can easily interface between Python and C++ using Boost.Python.
5,743,895
5,743,961
DllNotFound Exception when I use glut functions in my Dll
I have a c++ dll and c# application. In C# application I call function from dll. With simple function like: extern "C" { __declspec(dllexport) void HelloFromDll() { MessageBox(NULL, _T("Hello from DLL"), _T("Hello from DLL"), NULL); } } all works fine. When i use function with glut like this: exter...
Set your working directory of your application to the path of the DLL's, this should solve your problem.
5,744,016
5,744,637
Liboauth request is failing
I am trying with program code from http://liboauth.sourceforge.net/tests_2oauthexample_8c-example.html but every time I am getting "HTTP request for an oauth request-token failed.\n" I am behind proxy . what I need to edit to make it work behind proxy ?
I edit the code of lib file outh_http.c to include proxy details in curl request.
5,744,089
5,744,126
How to make cursor rotate
What i am trying to is to do something like this: Print \ then | then / then _ and it goes on in a loop. Here is my code: #include <stdio.h> int main() { while(1) { printf("\\"); printf("|"); printf("/"); printf("_"); } return 0; } The problem i face is t...
I don't properly understand what you mean by How to make cursor rotate? But were you by any chance wanting to do something like this: #include <stdio.h> #include <time.h> #define mydelay 100 void delay(int m) { clock_t wait = m+ clock(); while (wait > clock()); } int main() { while(1) { ...
5,744,280
5,744,299
Why same works for windows and doesn't work for unix?
In windows API to create process we have CreateProcess function. Now let's consider we want to create process and run DIR /X command. Of course in windows there is not executable DIR.exe and we can't just pass it to CreateProcess. So what to do? Solution of this problem is quite simple. We just should pass cmd /C "DIR...
Get rid of the quotes on the argument to sh: char *arg[] = {"sh", "-c", "ls | wc", NULL}; execvp(arg[0], arg);
5,744,334
5,744,669
std::bad_alloc when adding a struct to std::vector
this is probably something stupid, but i can't figure it out. I'm getting a std::bad_alloc exception in the following code snippet (which is a case statement in a switch): case 0: { MyPrimitiveNode* node = new MyPrimitiveNode( 1, false ); TheStack.push_back( MyStackItem( node, TYPE_REF ) ); // bad_alloc here break; } ...
That stack trace doesn't show anything that would lead me to believe that some part of the push_back is requesting a ton of memory. Therefore, that pretty much leaves the option that your program has corrupted the heap somewhere ELSE and this allocation is the victim. Without more code and details all I can suggest is ...
5,744,391
5,752,839
Why new and delete so slow in a loop under MSVC 2010
I got a problem when I tried to create and delete an instance of the class in a loop. Execution time of iterations is quite different. As I understand it, this is associated with the removal of objects from memory. However, the behavior of this operation I do not understand. Why time is different? How do I fix it? Time...
In addition to what other answers say you have to account for Visual C++ 10 runtime heap being thread-safe. This implies that even when you only have one thread you encounter some overhead facilitating heap operations being thread-safe. So one reason you see such poor results is that you use a universal but rather slow...
5,744,519
5,744,571
Loading screen animation using threads
I have made a game, it is written in C++ and directX. When the user chooses which mission to play the screen goes blank for some time while it load in all the resources. So the user knows the game has not crashed I want to make a loading screen with an animation. My question is this: If one thread (the main one) cras...
If one thread (the main one) crashes do all threads of that process crash? If the main thread crashes (i.e. the UI thread) obviously the application crashes. If any worker thread crashes, you will get an exception which you can choose to ignore. Can you destroy a thread from the thread that created it or does the th...
5,744,667
5,745,205
dupplicating std::ofstream appended content
I am using a std::ofstream for trace output. For some reasons, I sometimes want to dupplicate what I have appended at the end of the std::ofstream (that is not flushed or closed yet), into another std::ofstream; Do you think of any way of achieving this ? Thx
The Tee filter from Boost.Iostreams can split an output stream into two. Here's an example inspired heavily by the one given by Johannes Schaub in his answer here. #include <sstream> #include <iostream> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/tee.hpp> int main() { namespace io = boost::iost...
5,744,851
5,745,044
Running a 32bit Extended Stored Procedure on a 64bit Sqlserver 2008 R2
How can I run a 32bit Extended Stored Procedure on a 64bit Sqlserver 2008 R2. I do not have access to the source of this Extended Stored Procedure since this is legacy code from a third party application. I am currently getting the following error: Could not load the DLL D:\Program Files\Microsoft SQL Server\MSSQ...
The only fix I found for this is to run your code through a linked server in a 32-bit instance of SQL Server Express next to your 64-bit instance (32-bit instances can be installed on a 64-bit Windows server). Any version other than Express will do, but SQL Server Express adds no extra cost. Not the most elegant soluti...
5,744,929
5,745,531
OpenGL: All planets have the same speed around the sun when animating
I'm trying to make an animation of the Solarsystem in GLUT, but somehow all the planets are flying around the sun at the same speed, while they all have different values. I'm new at OpenGL/GLUT so if you could explain your answer it would be appreciated :) This is my animation method: void renderScene(void) { glClearD...
Your call order is wrong. So every planet will rotate around its center along the y axis. Take mercurius for example. glTranslatef(2.0, 0.0, 0.0);//Move to new position gluSphere(quad[1], 0.2f, 64, 64); glRotatef(360.0*DayOfYear/365.0, 0.0, 1.0, 0.0); //Rotate y axis The correct order should be glRotatef(360.0*DayOfY...
5,745,254
5,745,284
std::list Iterator doesn't get assigned
Sorry about the vague question title, but I have these typedefs here: typedef std::list<AnimationKeyframe> Timeline; typedef Timeline::iterator Keyframe; and let's say a class like this: class foo { Timeline timeline; Keyframe left,right; }; I also have a copy/assignment constructor because I'm storing iterators (a b...
It looks as though that is const (perhaps a const reference). begin() const returns a const_iterator, not an iterator. The reason there is no conversion from const_iterator to iterator is as follows: void foo(const std::vector<int> &vec) { std::vector<int>::iterator it = vec.begin(); // if this compiled... *it ...
5,745,345
5,745,440
Passing unspecialized template as a template parameter
Can i do something like template<class Key, class Data, class Compare = less<Key>, template<typename T> class Allocator<T> = allocator<T> > class mymap { typedef map<Key,Data,Compare,Allocator<pair<const Key, Data> > > storageMap; typedef vector<Data,Allocator<Data> > storageVector; } So template ...
Yes, here's a minimal compileable example: #include <map> #include <vector> using namespace std; template < class Key, class Data, class Compare = less<Key>, template <typename T> class Allocator = allocator > class mymap { public: typedef map<Key,Data,Compare,Allocator<pair<const Key, Data> > > st...
5,745,608
5,745,770
Is pimpl compatible with anonymous namespaces?
I am trying to use the pimpl pattern and define the implementation class in an anonymous namespace. Is this possible in C++? My failed attempt is described below. Is it possible to fix this without moving the implementation into a namespace with a name (or the global one)? class MyCalculatorImplementation; class MyCal...
No, the type must be at least declared before the pointer type can be used, and putting anonymous namespace in the header won't really work. But why would you want to do that, anyway? If you really really want to hide the implementation class, make it a private inner class, i.e. // .hpp struct Foo { Foo(); // ....
5,745,679
5,747,248
Win Mobile 5.0 Can't Debug and user WiFi
I have an app that I have to debug. It is C++ on Windows Mobile 5.0, and it uses a network connection via WiFi. (Visual Studio 2008.) Disconnected from USB and active sync the app connects to the network just fine, but as soon as I plug it into the cradle, (and consequently connect via ActiveSync) it automatically disa...
Don't use ActiveSync - debug directly through the WiFi connection.
5,745,852
5,745,872
Good book on design patterns and advanced programming that is not the Head First
Maybe I'm little morose, but I do not feel comfortable with that book. Anytime I ask someone for a good book on this subject they recommend me Head First. Is there another "excellent book" that is not the Head First ? More straightforward and less fun. Thanks in advance.
There's the classic Design Patterns: Elements of Reusable Object-Oriented Software, aka the "Gang of Four" (GoF) book. The Head First book is great for an introduction to the topic and makes it more approachable and less dry than the GoF book.
5,745,903
5,745,941
Compile C++ in linux
I'm trying to compile a simple application in linux. My main.cpp looks something like #include <string> #include <iostream> #include "Database.h" using namespace std; int main() { Database * db = new Database(); commandLineInterface(*db); return 0; } Where Database.h is my header and has a corresponding ...
Those are linker errors. It is complaining because it is trying to produce the final executable, but it cannot, because it has no object code for Database functions (the compiler does not infer that the function definitions corresponding to Database.h live in Database.cpp). Try this: g++ -std=c++0x main.cpp Database.c...
5,745,963
5,746,019
Chain value of string variable with some text and print it to standard output in C++
I want to do something really simple: I have function that has string parameter and I want to chain it to some constant string, then output result to console like this: void test(string s){ cout << "Parameter of this function was: " << s; } In other languages chaining like this works, but in C++ the compiler is un...
You probably forgot to #include <string> or #include <iostream>.
5,746,043
5,754,738
IWebBrowser2 and move hosting window
I use IWebBrowser2 to implement a GUI for my application. I have a custom frameless window which hosts IWebBrowser2. Javascript and window.external I use to communicate with the application. My question is how to implement moving my host window (with IWebBrowser2 of course)? I draw a pseudo-Header in html and I need to...
Don't use IWebBrowser2 directly for this. Instead, use the Win32 API. You can get a HWND with IWebBrowser2::get_HWND. With that, it's easy to subclass its windowproc (via SetWindowLong(GWL_WNDPROC)) and intercept WM_MOUSEMOVE.
5,746,076
5,746,200
In C++, does overriding an existing virtual function break ABI?
My library has two classes, a base class and a derived class. In the current version of the library the base class has a virtual function foo(), and the derived class does not override it. In the next version I'd like the derived class to override it. Does this break ABI? I know that introducing a new virtual function ...
It might. You're wrong regarding the offset. The offset in the vtable is determined already. What will happen is that the Derived class constructor will replace the function pointer at that offset with the Derived override (by switching the in-class v-pointer to a new v-table). So it is, normally, ABI compatible. There...
5,746,375
5,746,424
Looping twice is faster than looping once in C++?
Here is a small test I did and the result surprised me: doing the same loop twice was approximately twice as fast as looping once. I am guessing it as because of memory access? float* A = new float[1000000]; float* B = new float[1000000]; int h,w; h = w = 1000; CString txt; double time1, time2; time1 = Timer::instance...
It could be CPU cache, but more likely it's the concurrent memory access. When you access array1[x], and then immediately after that array2[x], those are two very different locations in memory and it's difficult to optimize. However array[0], array[1], array[2] etc are all in contiguous memory and much more efficient t...
5,746,559
5,746,827
ring buffer without priority inversion
I have a high-priority process that needs to pass data to a low-priority process. I've written a basic ring buffer to handle the passing of data: class RingBuffer { public: RingBuffer(int size); ~RingBuffer(); int count() {return (size + end - start) % size;} void write(char *data, int bytes) { ...
What you have should be OK, as long as you adhere to these guidelines: Only one thread can do writes. Only one thread can do reads. Updates and accesses to start and end are atomic. This might be automatic, for example Microsoft states: Simple reads and writes to properly-aligned 32-bit variables are atomic oper...
5,747,072
5,747,246
Deviation in a deterministic application
I am currently working on a (legacy) programme that has been written in C++ and C#; it executes some heavyweight calculations but should be completly deterministic. i.e. the same inputs will yeild the same outputs... Problem is that 2 runs (on the same computer, using the same compiled executable) produce slightly diff...
Two ideas occur to me: uninitiased variables. floating point arithmetic is not associative. The latter point can yield machine accuracy level differences under multi-threading. It's much more likely to be uninitiased variables though!
5,747,317
5,748,123
Boost::asio::async_read doesn't stop on condition
I have some issue with boost::asio::async_read Here's my code void TCPConnection::listenForRead() { boost::asio::async_read(m_socket, boost::asio::buffer(m_inbound_data), boost::asio::transfer_at_least(64), boost::bind(&TCPConnect...
Boost.Asio will never resize your buffer. When you create a buffer from an std::vector<char>, the size of the buffer is the size of the vector. If you don't give it a size, it will be a zero-length buffer. The transfer_at_least functor returns true if either at least N bytes are in the buffer or the buffer is full. In ...
5,747,373
5,747,421
How to set the lower or higher Value of a int64?
I know i can get the higher Value of a int 64 with: int32 higher = (int32)(iGUID >> 32); But how can i set it? I tried it with this, but it says "expression must be a modifiable value": iGUID << 32 = inewlGUID; I need to keep the other Value, ( if i set the higher value, the lower should keep).
To change the upper 32 bits while keeping the lower ones unmodified: iGUID = (iGUID & 0xFFFFFFFF) | (inewlGUID << 32);
5,747,723
5,749,720
OpenGL view on C# Form
How to display a glut window inside Windows Form? glutCreateWindow("Example") create another form, glutCreateSubWindow(hwnd, 0, 0, 100, 100), where hwnd is handle to my main Window Form in C#, i get an AccessViolation Exception. The Glut program is in a C++ DLL. My application is on C# WPF. I need to display glut vie...
Looks like you're hosting a Win32 object in a WPF form. Yes, this requires workarounds. Have you seen the WPF and Win32 Interoperation guide on MSDN? http://msdn.microsoft.com/en-us/library/ms742522.aspx You'll need to check out the HwndHost class, too: http://msdn.microsoft.com/en-us/library/system.windows.interop.hwn...
5,748,117
5,748,554
Determine if a type has particular member function signature
template<typename U> struct CheckSignature { enum {SizeTrue = 1, SizeFalse = 2}; typedef char ReturnTrue[SizeTrue]; typedef char ReturnFalse[SizeFalse]; typedef typename U::iterator (U::*InsertSig)(typename U::iterator, typename const U::value_type &); static ReturnTrue &CheckInsert(InsertSig); ...
Try this instead: #include <string> #include <vector> #include <iostream> template<typename U> struct CheckSignature { enum {SizeTrue = 1, SizeFalse = 2}; typedef char ReturnTrue[SizeTrue]; typedef char ReturnFalse[SizeFalse]; typedef typename U::iterator (U::*InsertSig)(typename U::iterator, typename ...
5,748,129
5,883,790
Linux-app does not get UDP messages from 169.254.x.x (local link)
My application (written in C++, running on Ubuntu 9.10) is listening on a UDP socket for broadcast messages from external devices. Those devices can have any IP address, since the idea is to communicate beyond IP ranges. When the devices have IP addresses such as 99.99.1.2, 1.2.3.4, 0.0.0.1, 192.168.2.77 etc, it works ...
it seems that I found the reason. Anyway, thanks to those who suggested solutions. I didn't mention that my Ubuntu is running in a VM (which is basically not the problem since Wireshark got the messages) The interfaces are: eth2 is the interface I was talking about above (thus, which does the external communication via...
5,748,161
5,748,241
How can Qt Creator be used as general C++ IDE (no usage of Qt library)?
I've been looking around for a nice C++ IDE, and I really like the features and performance of Qt Creator, and I plan to use it to make Qt based applications down the road. However, for right now, I just want to use Qt creator as general purpose C++ IDE without the use of the Qt library. How can I go about using Qt cre...
I do it constantly. You have two options: use qmake project files: to get rid of all the remaining Qt stuff, add these to your project file(s): CONFIG -= qt DEFINES -= UNICODE QT_LARGEFILE_SUPPORT Remember that qmake itself is still required to build. So you'll most likely need a Qt installation. use Cmake project fi...
5,748,218
5,748,265
Proper syntax for a templated constructor using template template parameters
I'm trying to extend my (limited) understanding of class templates to class templates with template template parameters. This declaration and constructor works fine (well, it compiles): template < char PROTO > class Test { public: Test( void ); ~Test( void ); void doIt( unsigned char* lhs, unsigned char* rh...
Try this template< template<char v> class Char2Type > Test2<Char2Type>::Test2( void ) { } A template-argument for a template template-parameter shall be the name of a class template. Char2Type is the template-name whereas Char2Type<char> is the template-id. You are not allowed to use template-id in place of template...
5,748,264
5,748,316
Default arguments in c++
void volume(int l=10, int w=10, int h=10); int main() { clrscr(); volume(); //equivalent to volume(10,10,10) volume(5); //equivalent to volume(5,10,10) volume(8,6); //equivalent to volume(8,6,10) volume(6,7,8); getch(); return 0; } void volume(int l, int w, int h) { ...
Because the language is designed to work like that! Or are you asking how the compiler makes it work? The standard does not specify how it should work just that it should. But potentially one solution would be to generate four methods behind the scenes: void volume() { volume(10, 10, 10); } void volume(int l) { ...
5,748,598
5,748,645
How to find a graph augmenting path
I'm trying to implement the Ford-Fulkerson algorithm to compute the maximum flow in a flow network. One step of the algorithm is to find a path from the start node to the end node (also know as sink) with available capacity on all edges. Could you suggest a easy and understandable way to find the augmenting path? UPDA...
Read here. Basically use Breadth-first_search. Edit: path.push_back(v1); is at the wrong place. You will add all vertices of the graph to the path. The correct way is to store for each node which is the predecessor node. This way you can restore the found path. Also you can break the while clause when you reach the sin...
5,748,660
5,749,156
Is there a good double-precision small matrix SIMD library for x86?
I'm looking for a SIMD library focused small (4x4) matrix operations for graphics. There's lots of single precision ones out there, but I need to support both single and double precision. I've looked at Intel's IPP MX library, but I'd prefer something with source. I'm very interested in SSE3+ implementations of these p...
Maybe the Eigen library? It supports SSE 2/3/4, ARM NEON and AltiVec instruction set.
5,748,688
5,748,783
Any other way to Reverse String Without using array?
int main() { clrscr(); char c[80],d[80]; cout<<"Enter a string = "; cin.get(a,80); strcpy(c,a); strrev(a); if(strcmp(c,a)==0) cout<<"String = "<<c<< "is palindrome."; else cout<<c<<" is not palindrome"; getch(); return 0; } so there is...
#include <string> #include <algorithm> #include <iostream> int main() { std::string s; getline(std::cin, s); if (std::equal(s.begin(), s.end(), s.rbegin())) std::cout << s << " is a palindrome\n"; else std::cout << s << " is not a palindrome\n"; } No arrays, no pointers.
5,748,739
5,748,854
Shared libraries and language standards
AFAIK, neither C99 nor C++ standards are aware of shared libraries. Why is that? EDIT: What is a good practice of writing shared libs without duplicating Linux/Windows versions? Thanks.
I can think of a few reasons why this makes sense in 1999 (as in the case of C99) or even 2011: There are still systems where C and C++ are used that don't have shared libraries. (Think embedded.) If the standard mandated something, life is needlessly difficult for compiler/library implementers who are targetting pl...
5,748,767
5,749,648
Not receiving moveEvent from parent?
I have a widget (QLineEdit), I reimplemented its moveEvent to meet something that I want to, now, when I use that widget as the mainwindow (not a child of anything...) everything works like a charm, when that widget is a child of another QWidget, that event occurs only once, when that widget is created, am I missing so...
A widget receives a move event when changes its position. The position of a child widget is relevant to its parent. When your QLineEdit has no parent & you drag it around it changes it position, because its position is relevant to the desktop. When your QLineEdit is a child widget & you drag around the the parent widge...
5,748,983
5,749,025
Gang of Four - Design Patterns - are those pattern samples coded in outdated way?
So to clarify my question... each pattern in infamous GoF book - Design Patterns Elements of Reusable Object-Oriented Software - has its code samples in C++. Are those up to date? Or does nowadays code in C++ look very different? I'm asking that, because when I posted my code with my last question, lots of C++ devs t...
They are a little out-dated, yes. But part of the point of those books is that these patterns are useful in several different languages and with several different styles. So while the code is a little old in the tooth, the ideas behind it aren't, and those ideas are what's important in those books. I would like to see ...
5,749,382
5,750,936
How do I correctly load the char array of a grayscale BMP using CImage?
I have the following code: cout<<"Please enter the name of your BMP image file: "<<endl; cin>>fname; nP = fname.c_str(); CImage input = CImage(); input.Load(nP); // allocate space for host source image unsigned char *pHI, *pCI; width = input.GetWidth(); height = input.GetHeight(); pCI = (unsigned char *)input.GetBits...
First thing to check is that input.Load() is successful. It returns an HRESULT and you should check the value of this. It's going to be a clue as to what's going on. Link to CImage::Load() You can interpret what an HRESULT means here: Details on HRESULT Good luck, but more information is needed. After edit: Further ...
5,749,520
5,749,545
How do I declare an instance of my class?
I have a Parser.h, Parser.cpp file with functions in it the constructor is Parser::Parser(string filename){....} Now i want to use my parser in my functions.cpp file, where i made sure to #include "Parser.h" In my function i want to use the parser how do i make a new instance of it, this is what i have but i get sy...
#include "functions.h" Your header file name is Parser.h, not functions.h. So do this: #include "Parser.h" Then this: Parser parser("filename.txt"); //not Parser::Parser parser('filename.txt'); Use double-quotes, not single-quotes for string literals such as "filename.txt"
5,749,644
5,749,649
aggregate 'std::stringstream out' has incomplete type and cannot be defined [C++]
I am new to c++ please help me figure out what is wrong with this string c; stringstream out; //aggregate 'std::stringstream out' has incomplete type and cannot be //defined out << it->second; out << end1;//'end1' was not declared in this scope c = out.str();
You seem to be missing an include for stringstream. On top of that you have a typo out << end1; should read out << endl; l instead of 1.
5,749,732
5,749,766
dependency sort with detection of cyclic dependencies
Before you start throwing links to wikipedia and blogs in my face, please hear me out. I'm trying to find the optimal algorithm/function to do a dependency sort on... stuff. Each item has a list of its dependencies. I would like to have something iterator-based, but that's not very important. What is important is that ...
It's normally called a topological sort. Most books/papers/whatever that cover topological sorting will also cover cycle detection as a matter of course.
5,749,925
5,750,449
Porting SetTimer() and KillTimer() to C#?
I am trying to port some code from C++ to C#. I came across this in the C++ code: watchdogTimer = SetTimer(1,1000,NULL); ... KillTimer(watchdogTimer); What is this code doing, and how can this be ported to C#? Thanks.
The CWnd::SetTimer function you're looking at creates a timer that sends WM_TIMER events to the window. This is analogous to the System.Windows.Forms.Timer component in .NET. It behaves somewhat differently than the System.Timers.Timer. There are two differences that are particularly relevant: Windows.Forms.Timer calls...
5,749,942
5,749,998
Is there a good reason in C++ to refer to a property without changing it?
I'm using someone else's C++ app as a guide for my own C# application and I've come across a strange pattern: array[index].property; No assignment. Nothing evaluated. I assume this is a vestigial line, left over from when an assignment would have been done here. But I'm not sure. And seeing as I'm having problems, I'm...
The code you included fits a pattern that I call "This programmer is a goof rocket". The code either does nothing or there is a side effect on which the programmer is depending. In both cases, "This programmer is a goof rocket" is a good description of a programmer who codes like that. The case of "oh, the previous c...
5,750,005
5,750,029
Code breaks when I don't output the variable; works when I do. WHUT?
I don't really know what more to say about this. I have never, ever seen this happen. And it just boggles me what causes this. I figured you guys might have seen this before and now what silly thing I am doing. Notes about it: 'temp' is a variable the function is taking in. It is a Binary Tree Node (BTN). temp->d...
Make sure nTemp is initialized. I bet it isn't. The cout causes something "benign" to be placed in nTemp.
5,750,247
5,750,663
Find out the mime type and associated applications with Qt
How can I find out a mime-type or content-type of a given file? I cannot use the suffix because the file could be renamed. Possible additions would be categorizing them as jpg, gif, png and so on are image files and can be opened by editing applications, which has been set in the OS. Thank you in advance.
What platform? On *nix, you should refer to how the program file does it, which is based on a few heuristics including checks of the first few bytes of a file (many file formats start with a fixed header, including many image formats). If you're on Windows, the *nix file command is probably still instructive, even if ...
5,750,396
5,751,112
double parentheses around function parameter list
I have the following code, it compiles with gcc 4.4 with no warnings, and returns 42. template<typename T> struct foo { }; template<typename T> struct foo<void (T)> { enum { value = 42 }; }; int main() { return foo<void ((int))>::value; } Now, I see why it should work when the template parameter is void (int), b...
In this case, void ((int)) is identical to void (int). void ((int)) part in foo<void ((int))> is called type-id. According to §8.1/1, type-id is composed of type-specifier-seq and abstract-declarator. In void ((int)), type-specifier-seq is void and abstract-declarator is ((int)), and abstract-declarator can be parenthe...
5,750,549
5,750,611
Problem when using recursive_directory_iterator()
Why when I try to iterate all directories and subdirectories of a partition using recursive_directory_iterator() from Boost, when it reaches the end, Visual Studio 2010 gives me an Abort error ? path Path = "e:\\"; for(recursive_directory_iterator it(Path); it != recursive_directory_iterator(); ++it) { cout << *it ...
What version of Boost are you using? There was a bug related to empty directories until 1.35: https://svn.boost.org/trac/boost/ticket/1061 Is your directory (sometimes) empty?
5,750,655
5,750,720
Please help me find out why i am in an infinite loop?
this is a bisection root method double p1::root(double (*pf)(double k), int a, int b, double e) { // void nrerror(char error_text[]); double left = (double)a; double right = (double)b; double midpoint; do { midpoint = ((right+left)/2); if(pf(left) *pf(midpoint) <0){ right = midpoin...
I would suggest putting some printfs in an doing some tracing of where you are.
5,750,793
5,750,823
template class restriction
I'm wondering if there is any way to restrict generating code for a template using custom conditions in my case i want to function foo to be called only if template class T has inherieted by class bar(something like this) template <class T:public bar> void foo() { // do something }
You can restrict T though using "Substitution Failure Is Not An Error" (SFINAE): template <typename T> typename std::enable_if<std::is_base_of<bar, T>::value>::type foo() { } If T is not derived from bar, specialization of the function template will fail and it will not be considered during overload resolution. std:...
5,750,884
5,751,016
wcout not writing wide character out to command prompt
I am attempting to write the following character out in windows command prompt: ュ (U+FF6D). I am able to see the character get written out using WriteConsoleW. I am also able to see the character if i use WideCharToMultiByte using the CP_ACP code page (chcp returns 932: Japanese). However, when I attempt to use regular...
The default locale for C++ iostreams is always the "C" locale. From the C++03 standard, §27.4.2.3/4: locale getloc() const; If no locale has been imbued, a copy of the global C++ locale, locale(), in effect at the time of construction. From §22.1.1.2/1-2: locale() throw(); Default constructor: a snapshot of the curr...
5,750,970
5,788,584
How do you implement the factorial function in C++ with proper error handling?
I asked this before but it was closed by people who didn't understand the question. I'm not looking for just a loop, I am looking for how you would do it for production code with stuff like error handling for arguments and overflows. And please don't just say "use library X" unless you can link to the code for said lib...
Might be something as simple as: unsigned factorial(unsigned n) { if (n > theUpperThreshold) throw ExceptionFormYourMathLibrary("Explain that n! can't be represented by unsigned"); return lookupTable[n]; } Unless your math library provides some big integer class as well.
5,751,061
5,751,232
keyPressEvent() is not catching some keys on OSX
I am writing a program in Qt c++ and I'm having some problem handling key press events. When run on Linux (Ubuntu 10.10) or Windows 7 the application catches these key events just fine. However when I run the program on OSX 10.6.7 it doesn't catch any character keys, number keys, or the arrow keys. It does catch the ca...
You need to set the window's focus policy to get it to accept keys. Something like this: QMainWindow.setFocusPolicy ( Qt::StrongFocus );
5,751,107
5,751,127
Overloaded parenthesis operator
I'm using the EasyBMP library. I have a function that returns a BMP* object. BMP objects have the parenthesis overloaded, where I can do: BMP image; *image(x,y)->Red=0; But now that I'm trying to return a pointer, I want to do: BMP *image; *image(x,y)->Red=0; but I get an error saying that image cannot be used as a f...
BMP* image = getimageptr(); *(*image)(x,y)->Red=0; Or, perhaps better: BMP* image_ptr = getimageptr(); BMP& image = *image_ptr; *image(x,y)->Red=0; (BTW, do you really dereference that object returned by op() before dereferencing it again to access Red? Seems odd!)
5,751,220
5,751,229
Best way to strip off symbols
Last week I released the Linux and windows version of an application. And after the release we realized that the symbols were not stripped off, and my manager thinks (and I disagree) that it might allow the user to understand our algorithm. Anyway, now, I will have to clean-up the symbols and re-release the application...
With Visual C++ (and other Microsoft compilers) on Windows, symbols aren't part of the binaries. Instead, they are stored in separate files called "Program Database" files (.pdb files). Just don't provide the .pdb files. With the GNU toolchain you would use strip to remove symbols from the binaries.
5,751,268
5,751,288
Random numbers causing problems
Say I have a member variable vector<bool> rightWall;. rightWall has width*height indices. I want to access a random index of rightWall. So I do: index1=rand()%(width*height-1); rightWall[index1]=true; But I get Valgrind errors: Invalid read of size 8. rightWall was never initialized or anything, and I'm not sure it's ...
To get a vector of a certain size you need to initialize it like so: vector<bool> rightWall(width*height); or resize it: vector<bool> rightWall; rightWall.resize(width*height);
5,751,316
5,751,333
how to sort a vector of pairs?
I am trying to sort a vector of pair<int, T> (where T is the templated value type of the class) and codeblocks is giving me massive amounts of errors i dont understand why. is there there some special syntax required to sort vector<pair<int, T> >? i did make the comparison function, which did not use T at all here's th...
The posted code didn't compile but when I was trying to make it compile I noticed you probably want: order.push_back(std::make_pair(level, root -> value)); Also: int max_level = order[order.size() - 1]. first; This fixed version of yours compiles for me: #include <iostream> #include <algorithm> #include <vector> usin...
5,751,502
5,751,536
what is the best program to view process memory map?
I need to view image/heap/malloc()/stack and other resources used by process. I knew about Memory Validator but it lacks some of features.
Checkout the tools from Sys Internals. http://technet.microsoft.com/en-us/sysinternals/bb545027 Namely RamMap and VMMap. If you can state what features you're looking for, then it would help to provide a better solution.
5,751,698
5,751,708
Memory debugger for c++ on mac?
I'm developing a mac application in C++, and I'm having the following problem: words(26222,0xa0b5c540) malloc: *** error for object 0x88dda04: incorrect checksum for freed object - object was probably modified after being freed. *** set a breakpoint in malloc_error_break to debug Anyway, I set a breakpoint in mall...
Valgrind is the standard open-source memory debugging tool. :-)
5,751,737
5,751,755
boost::thread_resource_error when more than 32705 threads
I'm implementing a message passing algorithm. The messages propagate through the nodes of the graph, blocking until they have have received enough information (from other neighbours) to send a message. The algorithm is easy to write if I put each message in its own thread and use a boost::condition to pause the thread...
I think with 32K threads on the system, you should look at potential solutions other than how to have more threads. For example, a thread pool (Boost has some things for this). Anyway, on your system, aren't PIDs limited to 32768 or some such value? You're going to run out sooner or later, may as well design the syst...
5,751,749
5,751,874
How can I read BMP pixel values into an array?
I'm writing code in C++ (on Windows) and I'm trying to extract the pixel values of a grayscale bmp. I don't care about keeping any of the metadata, and just want to store the pixel values in a char array. I haven't been able to find a standard or "typical" way of doing this manually, so I'm wondering if there's perhaps...
Read the entire file into memory. There will be a small header at the front, and the rest of it will be the pixel values. The first part will be a BITMAPFILEHEADER structure. The only part you care about is the bfOffBits, which gives the number of bytes from the start of the file to the pixel values. The next part afte...
5,751,779
5,752,848
Cannot create a breakpoint in a file using gdb
gdb GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-32.el5_6.2) g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-50) Compiling with the following cflags: CFLAGS = -Wall -Wextra -Wunreachable-code -ggdb -O0 I have also tried using just -g as well, but that didn't work either. I have a file call demo.cpp and I am trying to create...
There's a mistake in your makefile - CLFAGS instead of CFLAGS in the recipe for demo.o. You should be able to catch that if you watch the output when you run make - you'll see missing compiler options when building just that one object, since CLFAGS is an empty variable. And of course, there's something to be said for ...
5,751,852
5,751,925
Using placement new in a Vector Container
If I have a container: std::vector<T*> elements; can I use placement new to allocate my objects so that the objects are all allocated contiguously? So that I can do something like this: size_t elementIndex = someRandomElement - elements[0]; Where someRandomeElement is a random element from elements and elementIndex w...
To make your pointed-to objects contiguous, you have two reasonable options: use new[] to create a single array of elements big enough to hold them all, then assign new values into them and put their addresses into elements use malloc() to create a big enough uninitialised memory area to hold them all (it will likely ...
5,751,970
5,752,022
C++: Derived virtual function is returning strange results
I created a derivable class with a virtual function in a .HPP file, and then gave it a default return value in the class's .CPP file. Next, I created a class which inherited the latter derivable class and overloaded it's virtual function, giving it a new return value. However, the return value is not always the same (e...
ostream& operator<<(ostream& a, Fruit b) This code constructs a new object of type Fruit using the constructor defined as Fruit(const Fruit&);. An Apple is a Fruit, so it can be used as the argument to the Fruit copy constructor, however, the Fruit copy constructor makes a regular Fruit regardless of the subclass of F...
5,751,972
5,751,995
is strtoul not endian safe?
So I am doing a conversion from a string to an unsigned long using strtoul on both a little endian and big endian machine. The little endian machine returns the correct value, while the big endian machine does not. Is this function truly not compatible on big endian machines? If so, is there a work around? Code: printf...
strtoul returns ULONG_MAX on overflow. That's what you are hitting. I'm assuming one is running on 32bit the other on 64bit on top of the Endianess differences. 4294967295 == 0xFFFFFFFF, which for a 32bit machine would be ULONG_MAX. Try whether the following works for you on both systems. I could only test it on a 64b...
5,751,977
5,751,990
Local type as template arguments in C++
This is my code #include <vector> template <typename T, template<typename> class C = std::vector > struct FooBar { /*codez*/ }; template<typename T> struct Global{}; int main() { struct Local{}; FooBar<Local,Global> k; } This is the error that I get template argument for ‘template<class T, template<class> ...
Which part of the standard says that this is wrong? That would be §14.3.1/2 from the 2003 C++ Standard: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter. How can make this code work? Don't use...
5,752,057
5,752,083
Why deleteing a pointer twice will cause crash?
Possible Duplicate: Why Free crashes when called twice I just want to know what exactly happened when we delete the pointer that already been deleted, and what cause the crash?
It's hard to predict exactly what will happen -- it depends a little on the compiler, and a lot on the standard library. Officially, it's just undefined behavior, so nearly anything can happen. The most common thing that'll happen is that the heap will get trashed. It may not check that what delete is valid, so when it...
5,752,081
5,752,106
Why can't we free() memory that was allocated by new?
I know free() won't call the destructor, but what else will this cause besides that the member variable won't be destructed properly? Also, what if we delete a pointer that is allocated by malloc?
It is implementation defined whether new uses malloc under the hood. Mixing new with free and malloc with delete could cause a catastrophic failure at runtime if the code was ported to a new machine, a new compiler, or even a new version of the same compiler.
5,752,191
5,752,221
std::getline for a comma delimited table file with quotations around certain fields
I'm basically running the following code. This code goes through line by line and grabs the different fields of a generic comma-delimited table file. My problem is that sometimes the "title" field can have commas in it. When it does, it's surrounded by quotation marks like so: "this, this is my title". But when my code...
Doing this well is kind of complex. Basically, you read the first character. If it's not a quote, then you read to the next comma. If it is a quote, you read to the next quote. Then you peek at the next character, and see if it's another quote. If it is, you read to the next quote again, and add what you read onto the ...
5,752,215
5,752,223
Can someone help me with nested-name specifiers in C++ templates?
What's wrong with the following sample code? It doesn't compile in GCC. Why? template <class TA> struct A { template <class TAB> struct B; }; template <class TC> struct C {}; template <class TD> struct D { template <class TTD> class T {}; }; template<class TA> template<class TBA> struct A<TA>::B : C<ty...
struct A<TA>::B : C<typename D<TA>::template T<TBA> > For a template-name to be explicitly qualified by the template arguments, the name must be known to refer to a template. When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-...
5,752,232
5,752,374
Detecting underflow during execution
Is there any way to detect underflow automatically during execution? Specifically I believe there should be a compiler option to generate code that checks for underflows and similar falgs right after mathematical operations that could cause them. I'm talking about the G++ compiler.
C99/C++11 have floating point control functions (e.g. fetestexcept) and defined flags (including FE_UNDERFLOW) that should let you detect floating point underflow reasonably portably (i.e., with any compiler/library that supports these). Though they're not as portable, gcc has an feenableexcept that will let you set fl...
5,752,239
5,752,332
What kind of book keeping does the OS do when we use new to allocate memory?
Besides remembering the address of the pointer of the object, I think the OS also need to record how large the size of the memory is. So that when we use delete, the os will know how much memory to free. Can anyone tell me more details about this? What other information are recorded? And where are those information sto...
As already noted, new is a library function, not an OS feature. The general case is approximately like this: The C++ compiler translates the new keyword into function calls to malloc() (or equivalent) The allocator keeps a list of free blocks of memory, it searches there for the best match. Typically, the 'best' match...
5,752,408
5,752,715
Qt: Resize borderless widget
My question is basically the same as this one, but applied to the Qt C++ framework. I am implementing a popup window by inheriting QWidget with flags Qt::QPopup | Qt::QWindow. I would like this window to be moveable and resizeable, I'm currently achieving this by using the mouse events in the following code: void Te...
You can add the resize grip by calling QDialog's or QStatusBar's function setSizeGripEnabled (or directly in QtCreator form designer). For custom widgets the simplest way probably is to use QSizeGrip. I didn't use it myself but you can check the Qt source code on git for QStatusBar or QDialog.
5,752,685
5,752,714
VC++2010 Automatically generate method stub or prototype
I'm new to C++ and Visual Studio, coming from Java and Eclipse; Say I write a new method for a class. Is there a shortcut or some quick way to automatically add the method prototype to the class definition in the header? Likewise, if i add a new method prototype to the header, is there a shortcut to generate a method s...
I don't know if VS 2010 has this feature, previous versions did not. But the problem can be addressed by 3rd party extensions. Visual Assist X has the commands "Create Declaration" and "Create Implementation".
5,752,720
5,752,745
How to store a C++ object in C code?
I have C code that calls C++ code. The C++ code creates an object and then passes it back to the C code, which stores the object in a struct: extern "C" void cppFn(?** objectPtr) { *objectPtr = new Object(); } void cFn() { THESTRUCT theStruct = {0}; cppFn(&(theStruct.objectPtr)); } typedef struct THESTRUC...
void. Like so: typedef struct THESTRUCT { void* objectPtr; } THESTRUCT; void* is a "generic" pointer type. (You have to cast it to some other type to use it. Since there is no type to cast it to at the C end, it's effectively an opaque pointer.) Another approach is to make a forward declaration for your C++ type, ...
5,752,794
5,752,861
error: void value not ignored as it ought to be - C/GTK+
I am trying to create a window in GTK+ that has tab looks like this: Whenever the user clicks in the "New" button, there is a new tab appear. However, when I was compiling my program I got an error: void value not ignored as it ought to be phongcao@phongcao:~$ g++ /home/phongcao/C++/GTK+/newtab.cc -o /home/phongcao/C+...
The line number doesn't make much sense to me but I think your problem is right here (reformatted for illustrative purposes): g_signal_connect(G_OBJECT(button), "new_tab", G_CALLBACK(new_tab(GTK_NOTEBOOK(notebook), content, hbox)), /* <== Badness */ NULL ); You're calling the new_tab function inside the G_CALL...
5,753,000
5,753,043
Why do IUnknown* pointers retrieved through different interfaces of the same COM object have the same value?
I have the following hierarchy of COM interfaces and a class implementing them: interface IX : public IUnknown{}; interface IY : public IUnknown{}; class CA: public IX, public IY{}; Here class CA effectively inherits from IUnknown twice. We know there are two vtable pointers in class CA - one is pointed to IX and anot...
That's so called "object identity" requirement that states that whenever you request IUnknown from two objects you get distinct pointers if those are distinct objects and equal pointers if that's the same object. Every QueryInterface() implementation must fulfill this requirement. This is usually done by choosing which...
5,753,258
5,753,519
Super odd C++ black hole in int and float
Basically im trying to enter a value into the console, and output the decimal point as a whole number, and thats what needs to essentially occur. I've developed a way to do this, using float, int and simple maths. I'm still new to C++ but this error is not making sense. If you enter 0.01, 0.02, 0.03, 0.04, 0.06 or 0.08...
The inherent problem with float precision is amplified by the default truncation rounding in C and C++, which rounds e.g. 0.999999 to 0. You can make things more robust by rounding instead of truncating: int decimal = 0.5f + to_decimal * 100; You could also use a small value like 1e-6 instead of 0.5 to get a more robu...
5,753,271
5,753,289
How to convert char to it's ascii binary code
All I want is to go from 'a' to 0110 0001
if you write int i = 'a'; you get you want since all numbers physically are base 2. But if it's needed to get a string with ones and zeros then here is an example /* itoa example */ #include <stdio.h> #include <stdlib.h> int main () { int i = 'a'; char buffer [33]; //the variable you will store i's new value (bina...
5,753,833
5,753,882
C++: overriding public\private inheritance
If B inherits from A using public, can B override one of the functions and force it to be private? class A { public: virtual double my_func1(int i); virtual double my_func2(int i); } class B : public A // Notice the public inheritance { public: virtual double my_func1(int i); private: virtual double my...
If B inherits from A using public, can B override one of the functions and force it to be private? NO Eventhough the my_func1() is declared under priavte access specifier it can be still called through a pointer to class A, actually pointing to a object of class B The call to my_func1() is evaluated at run time depen...
5,754,055
5,834,461
make with g++/intel C++ compiler calling fortran functions
I have been trying to call some functions from a library provided by a commercial finite element code. The examples on using this library are being compiled with intel fortran compiler for my type of system so I am using intel c++ compiler to link the object files, I have set up a simple test case with the extern decle...
I think you might be getting caught by the strings you are passing. When passing strings between Fortran and C++, you need to account for the hidden length argument. The prototypes you show for binset_ and binclo_ do not include this. By default, when Fortran passes arguments, they are all passed by reference except ...
5,754,134
5,754,142
Strange output on using scanf
#include <cstdio> int main() { int i; printf("%d", scanf("%d", &i)); } Whatever number i input, i get the output: 1 Why is it so?
On success, the scanf function returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned. Try this as well: printf("%d",scanf("%d%...
5,754,228
5,754,442
Non-threaded alternative to waiting on a condition. (Edit: Proactor pattern with boost.asio?)
I am implementing a message passing algorithm. Messages pass between adjacent nodes when they have enough information at the node to compose the message - information that is passed to the node from neighbouring nodes. The implementation is trivial if I make each of messages a thread and use boost::condition to put t...
I guess what you are looking for is the reactor pattern. This is where most of the activities do not take too much time and they are doing co-operative multitasking. See node.js for a JavaScript implementation of the idea, but in C++ the ACE library provides this concept out-of-the-box allowing multiple threads based o...
5,754,232
5,754,244
C++: Calling a non-const function in an object pointed from a const pointer (error C2662)
I have a struct with a const pointer to an object. It is const so that the pointer won't change, I do not wish to have the object constant. I'd like to call a non-constant function in that object, thus receiving the following error: error C2662: 'my_namespace::MyClass::myFunc' : cannot convert 'this' pointer from ...
Change your struct to: struct MyStruct { MyStruct( const MyClass* init_my_class_ptr ); MyClass* const my_class_ptr; }; That will make the pointer, instead of the pointee, const. More elaborate explanation (also see Wikipedia): the const keyword is applied to whatever comes before it, except in case there's not...