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,240,284
3,240,292
qt example from the book
I have this snippet of the code: #include <QApplication> #include <QFont> #include <QPushButton> #include <QWidget> class MyWidget : public QWidget { public: MyWidget(QWidget *parent = 0); }; MyWidget::MyWidget(QWidget *parent) : QWidget(parent) { setFixedSize(200, 120); QPushButton *quit = new QPushButton(tr("Quit"), this); quit->setGeometry(62, 40, 75, 30); quit->setFont(QFont("Times", 18, QFont::Bold)); connect(quit, SIGNAL(clicked()), qApp, SLOT(quit())); } int main(int argc, char *argv[]) { QApplication app(argc, argv); MyWidget widget; widget.show(); return app.exec(); } can somebody please explain what exactly is going on in this line MyWidget(QWidget *parent = 0); a little bit difficult understand what is this parent, thanks in advance
That is an argument to the constructor with a default argument (NULL since NULL is defined as 0 as per the c++ standard). Default meaning passing no parameter is the same as passing NULL. Since Qt's widgets are arranged in a hierarchal system (parent -> child relationships) parent is the widget which is the "owner" or "container" of the current one (NULL means no parent aka a root widget of sorts). For GUI items a widget will often have the widget it is contained in as its parent. This is advantageous since when a parent is deleted, it will delete any children is has automatically removing the need for much of the memory management that comes with c++.
3,240,556
3,241,582
Windows: Get LCID from locale string?
I have string data representing locales, like "fr" or "en". I need to convert it to the appropriate LCID values, like 0x80c or 0x409. Is there a function or macro to do so? I'm using C++ on Windows 7.
Those are LCID values, not sure what LID means. You can get them out of GetLocaleInfoEx(), available in Vista and up. You need to pass a locale name like "en-US", necessary to nail down the language locale. For example: #include "stdafx.h" #include <windows.h> #include <assert.h> int _tmain(int argc, _TCHAR* argv[]) { LCID lcid = 0; BOOL ok = GetLocaleInfoEx(L"en-US", LOCALE_RETURN_NUMBER | LOCALE_ILANGUAGE, (LPWSTR)&lcid, sizeof(lcid)); assert(ok); wprintf(L"LCID = %04x\n", lcid); return 0; } Output: LCID = 0409
3,240,681
3,240,811
C++ syntax/legality of inheriting from a template while also specifying type
How can I accomplish what is suggested by the following?: template<typename T> class Base{...}; ... class Derived : public Base<int>{...};
Yes, it's legal. Base is a class template, and when provided all its template parameters it can be instantiated, which makes it an instantiated class. So Base<int> is a class name, and you can inherit from it just fine.
3,240,707
3,240,743
Enum vs Macro States C++
(Question is related to my previous questions here, here, here, and here). I am maintaining a very old application that was ported years ago from DOS to Windows, but a lot of the old C conventions still carry forward. The one particular convention is a setBit and clrBit macro: #ifndef setBit #define setBit(word, mask) word |= mask #endif #ifndef clrBit #define clrBit(word, mask) word &= ~mask #endif I found that I could declare a variable as an enum type and set my variable equal to the one of the enumerated values that are defined. enum SystemStatus { SYSTEM_ONLINE = BIT0, SYSTEM_STATUS2 = BIT1, SYSTEM_STATUS3 = BIT2, SYSTEM_STATUS4 = BIT3 }; With BIT0 = 0x00000001, BIT1 = 0x00000002, etc. SystemStatus systemStatus; systemStatus = SYSTEM_ONLINE In your opinion, is using the setBit and clrBit macros more C like or C++ like - and would it be better to simply declare variables as an enumerated type and get rid of all the old setBit/clrBit stuff?
I think you're confusing the purposes. The enum is about setting up values to use as flags. setBit and clrBit are about operating on data. That data might happen to be a flag, but that's really the only relationship between the two ideas. That being said, macros are certainly NOT the C++ way of doing things. You would use inline functions instead. For example: template<typename T> inline T& setBit(T& word, T mask) { return word |= mask; } template<typename T> inline T& clrBit(T& word, T mask) { return word &= ~mask; } Edit to fend off nitpickers: This is just an example of how you could implement the functions. You don't need to use templates, you can use two template parameters instead of 1, you can use a void function or values instead of references if you want, (though then it would lose some of the original semantics). The main point is to get the benefits of type safety which you won't find in macros (among many other downsides of macros). http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.5 Edit: Here's a void, non-template version for comparison inline void setBit(unsigned int word, unsigned int mask) { word |= mask; } inline void clrBit(unsigned int word, unsigned int mask) { word &= ~mask; }
3,240,846
3,240,882
Do you know a tool for c++ program that shows which program line allocated how much heap?
I have a c++ program that dies because of out of memory error. Do you know a tool for c++ program that shows which program line allocated how much heap? I would like to figure which part of the program consumes most of the heap. Thanks. Platform: Microsoft C++...Windows By the way, can heap corruption cause excessive memory usage? Solution: It was not heap corruption. Some uninitialised variables were used to allocated the amount of memory. I used valgrind which showed the problem immediately (both the presence of huge allocations and uninitilased variables).
You could use something like valgrind on *nix platform or crtdbg checks on windows platform.
3,241,035
3,241,204
Using C++ templates or macros for compile time function generation
I have a code that runs on an embedded system and it has to run really fast. I know C and macros, and this particular project is coded mostly in C but it also uses C++ templates [increasingly more]. There is an inline function: inline my_t read_memory(uint32 addr) { #if (CURRENT_STATE & OPTIMIZE_BITMAP) return readOptimized(addr); #else return MEMORY[addr]; #endif } This function reads from memory in an optimized fashion or conventional fashion based on the current state and a bitmap that tells whether to use optimization in a specific state or not. #define STATE_A 0x0001 #define STATE_B 0x0010 #define STATE_C 0x0100 #define STATE_D 0x1000 #define OPTIMIZE_BITMAP 0x1010 // optimize states d and b and during the course of execution (ok, compilation), I tried to redefine CURRENT_STATE like so: int main(){ #define CURRENT_STATE STATE_A do_a(); #undef CURRENT_STATE #define CURRENT_STATE STATE_B do_b(); .... } All do_X() functions make read_memory() calls. I could not make this approach work. The value of current state is always STATE_A as I can see when I use #warning statements. This is not my question, although if you can help me with this I'll be double happy. So, my question is, is there a way to do this kind of thing using templates instead of macros? Some more info: I have to use an inline function because I cannot export MEMORY[] and this is a library function. I really prefer not to modify the function prototype (like read_memory()...) but it will do. Also, pardon my obscurity. many thanks,
The inline function will be parsed once, at the point in the translation unit where it is declared, and the state of the macros at that point will be used. Calling the function multiple times with the macros defined differently will not change the definition of the function. You can do this with a template though --- if you pass the "current state" as a template parameter then you can use a different instantiation at each call point: template<unsigned state> inline my_t read_memory(uint32 addr) { if(state & OPTIMIZE_BITMAP) return readOptimized(addr); else return MEMORY[addr]; } int main(){ read_memory<STATE_A>(some_addr); read_memory<STATE_B>(some_addr); .... } The compiler will realise that state & OPTIMIZE_BITMAP is a constant and optimize out one or other branch of the if for each template instantiation.
3,241,190
3,241,395
how to append a matrix to the end of another matrix? (using Boost Libraries in C++)
I have this: using namespace boost::numeric::ublas; matrix<double> m (3, 2); int k = 0; for (int j = 0; j < m.size1 (); j++) { for (int i = 0; i < m.size2 (); i++) m (j, i) = k++; } m = 0 1 2 3 4 5 And I need to append another matrix m2 to m matrix<double> m2 (3, 1); k = 0; for (int i = 0; i < m2.size2 (); i++) m (i, 0) = k++; m2 = 0 1 2 So, what I need to do to have this m = 0 1 0 2 3 1 4 5 2 Where can I find more information about operations like this? I ask because the information on http://www.boost.org/doc/libs/1_43_0/libs/numeric/ublas/doc/index.htm resembles more like an API, and it has not been so useful so far.
Well, this is not elegant, but is my first try: m.resize(m.size1(), m.size2()+1, true); column(m, m.size2()) = column(m2, 0); and, of course it needs to be adjusted if m2 has more than one column (or if there are differences in size1 between the two matrices)
3,241,307
3,241,332
About the copy constructor and pointers
I'm reading through an example in primer and something which it talks about is not happening. Specifically, any implicit shallow copy is supposed to copy over the address of a pointer, not just the value of what is being pointed to (thus the same memory address). However, each of the pos properties are pointing to two different memory addresses (so I am able to change the value of one without affecting the other). What am I doing wrong? Header #include "stdafx.h" #include <iostream> class Yak { public: int hour; char * pos; const Yak & toz(const Yak & yk); Yak(); }; END HEADER using namespace std; const Yak & Yak:: toz(const Yak & yk) { return *this; } Yak::Yak() { pos = new char[20]; } int _tmain(int argc, _TCHAR* argv[]) { Yak tom; tom.pos="Hi"; Yak blak = tom.toz(tom); cout << &blak.pos << endl; cout << &tom.pos << endl; system("pause"); return 0; }
You're printing the addresses of the pointers, not the address of the string they're pointing to: cout << &blak.pos << endl; cout << &tom.pos << endl; They are two different pointers, so their addresses differ. However, they point to the same string: cout << static_cast<void*>(blak.pos) << endl; cout << static_cast<void*>(tom.pos) << endl; (Note that cast static_cast<void*>(tom.pos). As Aaron pointed out in a comment, it is necessary because when outputting a char* will through operator<<, the stream library will assume the character pointed to to be the first character of a zero-terminated string. Outputting a void*, OTOH, will output the address.) Note that there is more wrong with your code. Here Yak tom; You are creating a new object. Its constructor allocates 20 characters, and stores their address in tom.pos. In the very next line tom.pos="Hi"; you are assigning the address of a string literal to tom.pos, thereby discarding the address of the bytes you allocated, effectively leaking that memory. Also note that Yak has no destructor, so even if you don't discard the 20 characters that way, when tom goes out of scope, tom.pos will be destroyed and thus the address of those 20 bytes lost. However, due to your missing copy constructor, when you copy a Yak object, you end up with two of them having their pos element pointing to the same allocated memory. When they go out of scope, they'd both try to delete that memory, which is fatal. To cut this short: Use std::string. It's much easier. Get a grip on the basics, using safe features of the language like the std::string, the containers of the stdandard library, smart pointers. Once you feel sure with these, tackle manual memory management. However, keep in mind that I, doing C++ for about 15 years, consider manual resource management (memory is but one resource) error-prone and try to avoid it. If I have to do it, I hide each resource behind an object managing it - effectively falling back to automatic memory management. :) Which "primer" is this you're reading? Lippmann's C++ Primer? If so, which edition? I'd be surprised if a recent edition of Lippmann's book would let you lose onto dynamic memory without first showing your the tools to tackle this and how to use them.
3,241,464
3,241,500
Find count of overlapping 1 bits
I'm trying to find the number of overlapping 1 bits between 2 given numbers. For example, given 5 and 6: 5 // 101 6 // 110 There is 1 overlapping 1 bit (the first bit) I have following code #include <iostream> using namespace std; int main() { int a,b; int count = 0; cin >> a >> b; while (a & b != 0) { count++; a >>= 1; b >>= 1; } cout << count << endl; return 0; } But when I entered 335 and 123 it returned 7 but I think it is not correct Can someone see a problem with my code?
The problem is that you're just printing out the number of times any of the bits match, as you lop off the least significant bit for each iteration (which will at max be the number of bits set for the smaller number). You're comparing all bits of [a] BITWISE AND [b] each iteration. You could rectify this by masking with 1: a & b & 1, so that while you're shift thing bits rightward each time, you're only checking if the least significant bit is being checked: while (a && b){ count += a & b & 1; a>>=1; b>>=1; }
3,241,494
3,241,823
ptr_vector - _CrtDumpMemoryLeaks() - memory leaks even though destructor is called
I'm working on a game engine and in an earlier question it was suggested that I start using boost::ptr_vector to maintain a list of pointers. The basic idea is to have several State's, each State has a SceneGraph. Each state has several resources that they initialize, and then stuff its own SceneGraph. The SceneGraph has a boost::ptr_vector that it stuffs the resource pointers in. Here's the relevant code: Resource creation and addition to the SceneGraph in TestState backgroundImage = new DEBUG_NEW Fenris::Node2D::Image(std::string("backgroundImage"), std::string("../media/img/background.jpg")); sceneGraph->addNode(backgroundImage, Fenris::Core::STRATUM_BACK); SceneGraph boost::ptr_vector<SceneGraphNode> backStratumList; // The add() method void addNode(SceneGraphNode *pNode, STRATUM_TYPE stratumType) { switch(stratumType) { case STRATUM_BACK: backStratumList.push_back(pNode); break; case STRATUM_NORMAL: normalStratumList.push_back(pNode); break; case STRATUM_FOREGROUND: foregroundStratumList.push_back(pNode); break; } } Edited main.cpp with relevant lines PlatformGame::State::TestState *testState = new DEBUG_NEW PlatformGame::State::TestState(std::string("testState")); // Clean up the previously registered state (deletes its sceneGraph -- verified that the destructor is in fact called via debugger) delete testState; // Dump memleak report if we're running in debug mode #ifdef _DEBUG _CrtDumpMemoryLeaks(); #endif I'm using _CrtDumpMemoryLeaks() to output a memory leak log report. The log report tells me I have a memory leak; Detected memory leaks! Dumping objects -> {174} normal block at 0x00A56630, 32 bytes long. Data: <../media/img/bac> 2E 2E 2F 6D 65 64 69 61 2F 69 6D 67 2F 62 61 63 {173} normal block at 0x00A565A0, 8 bytes long. Data: < c > A8 63 A5 00 00 00 00 00 Object dump complete. Is _CrtDumpMemoryLeaks() having trouble with boost::ptr_vector or have I done something wrong? The debugger tells me that State does invoke its destructor (which has; delete sceneGraph) and I've also verified that the SceneGraph's destructor is also invoked. Any help is greatly appreciated, I'd love to see an empty memory leak report :-)
It sure doesn't look like a vector you're leaking. Note that the string is readable, that's at least one hint. If you can get the number between the curly braces stable ("{173}") then you can get a breakpoint when the memory is allocated. Put this in your main() function: _crtBreakAlloc = 173; Use #include <crtdbg.h> if necessary. Repeat for 174 to find the other one.
3,241,577
3,241,651
Including extra libraries on the link line
When linking an executable, if it does not make reference to any of the symbols in one of the DLLs on the link line, will it still depend on that DLL at runtime? To make the question concrete, suppose I am building an application from Visual Studio project foo. Under Project Properties > Linker > Input > Additional Dependencies I have specified bar.lib, the import library for bar.dll, even though it is not required to link foo.exe successfully. Do I still need to distribute bar.dll with my application since I have marked it as a linking dependency?
No it is not required. A import library only a library and the EXE will include only the references to functions which are used. By the way to verify this you can use DUMPBIN.EXE utility or dependencies walker (see http://www.dependencywalker.com/) which are part of Visual Studio packages. Just type DUMPBIN.EXE foo.exe /imports or open foo.exe with the dependencies walker.
3,241,634
3,241,672
SIGALRM Timeout -- How does it affect existing operations?
I am currently using select() to act as a timer. I have network receive operations which occur within a loop, and every few seconds a processing operation needs to occur. As a result, the select() statement's timeout constantly changes -- decreasing to zero over time and then restarting at 3. rv = select(selectmonitor+1, &readnet, NULL, NULL, &helper.timeout()); As things come in on the network, the statement is repeated and the value passed to it by helper.timeout() decreases. Eventually, the value will either be equal to zero or the system will timeout, which will result in the processing function executing. However, I've noticed that this is quite resource intensive -- the value for helper.timeout() must be constantly calculated. When I am trying to receive a few thousand packets a second, the time it takes for this operation to be done results in packet loss. My new idea is using SIGALRM to resolve this. This would allow me to set a timer once and then react when it is set off. However, I'm confused as to how it will affect my program. When SIGALRM 'goes off', it will run a function which I specify. However, how will it interrupt my existing code? And once the function is done, how will my existing code (within the while statement) resume? Also, it would appear its impossible to set the SIGALRM signal to call a function within a class? Is this correct? I imagine I can call a function, which can in turn call a function within a class.. Thanks for any assistance ahead of time.
Use your SIGALRM handler to set a flag variable. Use sigaction instead of signal to set your signal handler. Do not set the SA_RESTART flag. With SA_RESTART not set your select statement will be interrupted by the signal. Your select will return -1 and errno will be EINTR. Since the signal might happen while your other code is executing you will want to check the flag variable too, probably right before going into the select. I was just reminded that this pattern can result in missing the signal, if it happens just after checking the flag and just before entering the select. To avoid that, you need to use sigprocmask to block the SIGALRM signal before entering the while loop. Then you use pselect instead of select. By giving pselect a signal mask with SIGALRM unmasked, the signal will end up always interrupting during the select instead of happening at any other time.
3,241,645
3,241,745
proper style for interfacing with legacy TCHAR code
I'm modifying someone else's code which uses TCHAR extensively. Is it better form to just use std::wstring in my code? wstring should be equivalent to TString on widechar platforms so I don't see an issue. The rationale being, its easier to use a raw wstring than to support TCHAR... e.g., using boost:wformat. Which style will be more clear to the next maintainer? I wasted several hours myself trying to understand string intricacies, it seems just using wstring would cut off half of the stuff you need to understand. typedef std::basic_string<TCHAR> TString; //on winxp, TCHAR resolves to wchar_t typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> > wstring; ...the only difference is the allocator. In the unlikely case that your program lands on a Window 9x machine, there's still an API layer that can translate your UTF-16 strings to 8-bit chars. There's no point left in using TCHAR for new code development. source
If you are only intending on targetting Unicode (wchar_t) platforms, you are better off using std::wstring. If you want to support multibyte and Unicode builds, you will need to use TString and similar. Also note that basic_string defaults the char_traits and allocator to one based on the passed in character type, so on builds where UNICODE (or _UNICODE, I can never remember which), TString and wstring will be the same. NOTE: If you are just passing the arguments to various APIs and not doing any manipulations on them, you are better off using const wchar_t * instead of std::wstring directly (especially if mixing Win32, COM and standard C++ code) as you will end up doing less conversions and copying.
3,241,749
3,241,769
boost static_assert with message?
on 1.43 boost it seems that BOOST_STATIC_ASSERT just allows to put a boolean value, is there some alternative that allows me to display a message as well on the compile error?
MPL has BOOST_MPL_ASSERT_MSG. E.g. using GCC 4.2. with this: BOOST_MPL_ASSERT_MSG(false, THIS_DOESNT_WORK, (void)); ... results in: /path/to/file.cpp:42: error: no matching function for call to 'assertion_failed(mpl_::failed************ (function()::THIS_DOESNT_WORK::************)())'
3,241,781
3,241,880
Boost.Statechart - issue with documented method for choice points
As per the example in the documentation I made the following code that fails to compile because custom_reaction<> does not seem to match the concept expected as the third template parameter to state<>. How do I really make choice points? (I also asked this on the boost list) #include <boost/statechart/state_machine.hpp> #include <boost/statechart/simple_state.hpp> #include <boost/statechart/state.hpp> #include <boost/statechart/custom_reaction.hpp> #include <boost/statechart/event.hpp> #include <boost/statechart/transition.hpp> #include <boost/mpl/list.hpp> #include <iostream> namespace sc = boost::statechart; struct make_choice : sc::event< make_choice > {}; // universal choice point base class template template< class MostDerived, class Context > struct choice_point : sc::state< MostDerived, Context, sc::custom_reaction< make_choice > > { typedef sc::state< MostDerived, Context, sc::custom_reaction< make_choice > > base_type; typedef typename base_type::my_context my_context; typedef choice_point my_base; choice_point( my_context ctx ) : base_type( ctx ) { this->post_event( boost::intrusive_ptr< make_choice >( new make_choice() ) ); } }; // ... struct MyChoicePoint; struct Machine : sc::state_machine< Machine, MyChoicePoint > {}; struct Dest1 : sc::simple_state< Dest1, Machine > {}; struct Dest2 : sc::simple_state< Dest2, Machine > { Dest2() { std::cout << "Dest2\n"; } }; struct Dest3 : sc::simple_state< Dest3, Machine > {}; struct MyChoicePoint : choice_point< MyChoicePoint, Machine > { MyChoicePoint( my_context ctx ) : my_base( ctx ) {} sc::result react( const make_choice & ) { if ( 0 ) { return transit< Dest1 >(); } else if ( 1 ) { return transit< Dest2 >(); } else { return transit< Dest3 >(); } } }; int main() { Machine machine; machine.initiate(); std::cin.get(); }
I think I might have found the answer. I'll wait for verification from the boost list but it looks like the document is just wrong and if you follow the directions in the camera example for making custom reactions it works fine. Namely the choice_point template needs to change to this: // universal choice point base class template template< class MostDerived, class Context > struct choice_point : sc::state< MostDerived, Context > { typedef sc::state< MostDerived, Context > base_type; typedef typename base_type::my_context my_context; typedef choice_point my_base; typedef sc::custom_reaction<make_choice> reactions; choice_point( my_context ctx ) : base_type( ctx ) { this->post_event( boost::intrusive_ptr< make_choice >( new make_choice() ) ); } }; This appears to work but I'll wait a bit in case the experts tell me it's wrong.
3,241,899
3,241,906
What is the error in the following g++ class construction?
I receive a g++ error (undefined reference to 'SomeClass::SomeClass(int)' and 'SomeClass::~SomeClass') with the following: /* * SomeClass.h * */ #ifndef SOMECLASS_H_ #define SOMECLASS_H_ class SomeClass { public: SomeClass(); SomeClass(int someInt); ~SomeClass(); }; #endif /* SOMECLASS_H_ */ /* * SomeClass.cpp * */ #include "SomeClass.h" SomeClass::SomeClass() { } SomeClass::SomeClass(int someInt) { } SomeClass::~SomeClass() { } /* * main.cpp * */ #include "SomeClass.h" int main() { SomeClass::SomeClass someObject(1); return 0; }
SomeClass::SomeClass someObject(1); First of all that's not valid, because SomeClass::SomeClass names the constructor, and not the class type. Just say SomeClass. Then you probably forget to link against SomeClass.cpp's object file. Be sure to include it in the compiler command line when you compile the executable, or add it to the project config by whatever IDE you are using.
3,241,954
3,242,023
Performance of .Net function calling (C# F#) VS C++
Since F# 2.0 has become a part of VS2010 I take an interest in F#. I wondered what's the point of using it. I'd read a bit and I made a benchmark to measure functions calling. I have used Ackermann's function :) C# sealed class Program { public static int ackermann(int m, int n) { if (m == 0) return n + 1; if (m > 0 && n == 0) { return ackermann(m - 1, 1); } if (m > 0 && n > 0) { return ackermann(m - 1, ackermann(m, n - 1)); } return 0; } static void Main(string[] args) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Console.WriteLine("C# ackermann(3,10) = " + Program.ackermann(3, 10)); stopWatch.Stop(); Console.WriteLine("Time required for execution: " + stopWatch.ElapsedMilliseconds + "ms"); Console.ReadLine(); } } C++ class Program{ public: static inline int ackermann(int m, int n) { if(m == 0) return n + 1; if (m > 0 && n == 0) { return ackermann(m - 1, 1); } if (m > 0 && n > 0) { return ackermann(m - 1, ackermann(m, n - 1)); } return 0; } }; int _tmain(int argc, _TCHAR* argv[]) { clock_t start, end; start = clock(); std::cout << "CPP: ackermann(3,10) = " << Program::ackermann(3, 10) << std::endl; end = clock(); std::cout << "Time required for execution: " << (end-start) << " ms." << "\n\n"; int i; std::cin >> i; return 0; } F# // Ackermann let rec ackermann m n = if m = 0 then n + 1 elif m > 0 && n = 0 then ackermann (m - 1) 1 elif m > 0 && n > 0 then ackermann (m - 1) (ackermann m (n - 1)) else 0 open System.Diagnostics; let stopWatch = Stopwatch.StartNew() let x = ackermann 3 10 stopWatch.Stop(); printfn "F# ackermann(3,10) = %d" x printfn "Time required for execution: %f" stopWatch.Elapsed.TotalMilliseconds Java public class Main { public static int ackermann(int m, int n) { if (m==0) return n + 1; if (m>0 && n==0) { return ackermann(m - 1,1); } if (m>0 && n>0) { return ackermann(m - 1,ackermann(m,n - 1)); } return 0; } public static void main(String[] args) { System.out.println(Main.ackermann(3,10)); } } An then C# = 510ms c++ = 130ms F# = 185ms Java = Stackoverflow :) Is it the power of F# (except small amount of code) If we want to use .Net and gain a bit faster execution? Can I optimalize any of these codes (especially F#) ? UPDATE. I got rid off Console.WriteLine and run the C# code without the debugger: C# = 400ms
I believe that in this case, the difference between C# and F# is thanks to tail-call optimization. A tail-call is when you have a recursive call that is done as "the last thing" in a function. In this case, F# doesn't actually generate a call instruction, but instead compiles the code into a loop (because the call is the "last thing", we can reuse the current stack frame and just jump to the beginning of the method). In your implementation of ackermann, two of the calls are tail-calls and only one of them is not (the one where the result is passed as an argument to another ackermann call). This means that the F# version actually invokes a "call" instruction (much?) less often. In generall, the performance profile is roughly the same as performance profile of C#. There are quite a few posts related to F# vs. C# performance here: Is F# really better than C# for math?
3,242,255
3,242,271
Multiple Threads - do i need to lock on reading data?
look at this code: int data=5; void Thread1() { if(data==5) { //nothing } } void Thread2() { if(data==2) { //nothing } } in this case, do i need to use EnterCriticalSection/MutexLock before if(data==..) ?
If you are just reading the data then no locks required. If you are writing the data AND you care about the order data is read then you need to use CS to make sure the ordering is correct. (Note if the object has a more complex state that is not updated in an atomic operation then you may care more about the ordering of reads/writes).
3,242,256
3,242,553
How does GMP stores its integers, on an arbitrary number of bytes?
2^64 is still far from the "infinity" my ram/hard drive can handle... First I wonder how GMP works with memory/processor since it does some kind of shady optimisations... I was also wondering if there is a way of storing an integer (unsigned, it's easier) on an arbitrary number of bytes. For example, on 50 bytes, I would have a cap of 2^400 -1. The thing to do is to work well with carries to keep the number consistent from one byte to another, I have some idea about that, but I'm really not sure it would be the fastest way to do this. I'm not even sure if I'm right. I'm guessing GMP uses this kind of way to store its data, but I just want some (even little) explanation or some forwarding to some theory (I don't have any doctorate, so don't be tough).
GMP dynamically allocates space to represent numbers (and reallocates when it needs to grow). This is described in light detail in Integer Internals, in the GMP manual, it describes how it chunks up the representation into "limbs" and stores the limbs in an array. The description of the term "limbs" comes from GMP Basics: Nomenclature and Types: A limb means the part of a multi-precision number that fits in a single word. (We chose this word because a limb of the human body is analogous to a digit, only larger, and containing several digits.) Normally a limb contains 32 or 64 bits. The C data type for a limb is mp_limb_t. So, representing a number in GMP works by grouping a number of limbs together to represent the magnitude of the integer, stored with a sign bit (the sign bit is dual purposed to store the number of limbs). What does this mean to you? Well, normally an int64 is represented in 64 bits. Done. If you package a bunch of these together, you can significantly increase that. Put two together, 2^64*2^64, or 2^128. Add two more limbs and you get 2^256. That's a lot of numbers, stored in 4 words (plus the representation overhead). Of course, the representation of floats is more complicated (see here), storing the representation using a mantissa (consisting of a sign and magnitude) and an exponent.
3,242,284
3,242,346
Can I define a type based on the result of some calculation?
I perform some calculations, based on the result, I would like to either use a short int or int for some type of data for the remaining program. Can (/How can) this be done sensibly in C or C++? I don't really care about the amount of memory used (i.e., 2 or 4 bytes), my primary aim is to access generic arrays as if they contained data of this type. I would like to avoid code such as the following: char s[128]; if (result of preliminary calculations was A) *((int*) s) = 50; else *((short int*) s) = 50; to set the first 4 or 2 bytes of s. A conditional global typedef would be ideal: if (result of preliminary calculations was A) typedef int mytype; else typedef short int mytype; I am not that familiar with C++ class templates (yet). Do they apply to my problem? Would I have to change the declarations throughout my program (to myclass< > and myclass< >*)? Many thanks! Frank Edit: The values may not always be aligned. I.e, a int can start at position 21. Thanks for the answers.
For plain C, you could do this using function pointers: static union { s_int[32]; s_short[64]; s_char[128]; } s; static void set_s_int(int i, int n) { s.s_int[i] = n; } static int get_s_int(int i) { return s.s_int[i]; } static void set_s_short(int i, int n) { s.s_short[i] = n; } static int get_s_short(int i) { return s.s_short[i]; } static void (*set_s)(int, int); static int (*get_s)(int); Set them once based on the preliminary calculations: if (result of preliminary calculations was A) { set_s = set_s_int; get_s = get_s_int; } else { set_s = set_s_short; get_s = get_s_short; } Then just use the function pointers in the rest of the program: set_s(0, 50); /* Set entry 0 in array to 50 */ Your file writing function can directly reference s or s.s_char depending on how it works.
3,242,475
3,242,586
Controlling how parameters are sent to superclass constructor from subclass constructor declaration (C++)
Can it be done? I am looking for something different than using the member initialization list (because that is present in the definition, not necessarily the declaration). Something like class(args) : superclass(fn of args);
What you are asking makes no sense. In C++ each class has a constructor. For a constructor the declaration defines the parameters. For a constructor the definition defines how the parameters are used (like how they are passed to the base class). Example: Plop.h ============= class Point { public: Point(int x,int y); }; class MyPoint: public Point { public: MyPoint(int x); MyPoint(int x,int y); MyPoint(double z); }; Plop.cpp ======== Point::Point(int x,int y) {} MyPoint::MyPoint(int x): Point(x,x) {} MyPoint::MyPoint(int x,int y): Point(x*2,y-x) {} MyPoint::MyPoint(double z): Point(sin(z),cos(z)) {}
3,242,505
3,242,524
How to create service which restarts on crash
I am creating a service using CreateService. The service will run again fine if it happens to crash and I would like to have Windows restart the service if it crashes. I know it is possible to set this up from the services msc see below. How can I programatically configure the service to always restart if it happens to crash.
You want to call ChangeServiceConfig2 after you've installed the service. Set the second parameter to SERVICE_CONFIG_FAILURE_ACTIONS and pass in an instance of SERVICE_FAILURE_ACTIONS as the third parameter, something like this: int numBytes = sizeof(SERVICE_FAILURE_ACTIONS) + sizeof(SC_ACTION); std::vector<char> buffer(numBytes); SERVICE_FAILURE_ACTIONS *sfa = reinterpret_cast<SERVICE_FAILURE_ACTIONS *>(&buffer[0]); sfa.dwResetPeriod = INFINITE; sfa.cActions = 1; sfa.lpsaActions[0].Type = SC_ACTION_RESTART; sfa.lpsaActions[0].Delay = 5000; // wait 5 seconds before restarting ChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, sfa);
3,242,555
3,242,564
Overloading operator++ prefix / postfix in terms of each other?
I have a question that may have been answered over 9000 times before but I really don't know how to word it, this is what I am going to try. I've seen in some C++ books and tutorials that when defining your own class which has a iterable value (incrementable) semantics, you can overload operator++ for it (all I'm going t state here I'd guess applies for operator-- as well). The standard way of doing this seems to be: class MyClass { public: MyClass& operator++ () { increment_somehow(); return *this; } .... }; Where increment_somehow() well... somehow increments the object's value. Then, it is possible to define the postfix version of operator++ in a manner like this: MyClass operator++ (MyClass& it, int dummy) { MyClass copy(it); ++it; return copy; } It is all fine and dandy (I think I got that idiom right), but the problem is that doing all that for each class that defines operator++ quickly becomes tiresome and verbose, so I was thinking that I could take some advantage of a trick that I recently learnt when overloading operators. That is, making use of the <utility> header and a facility inside called rel_ops that I found out about yesterday (I just came back to C++ after four years of being away...): class MyClass { public: bool operator== (const MyClass& that) { return compare_for_equality_somehow(that); } bool operator< (const MyClass& that) { return compare_for_lessality_somehow(that); } .... using namespace std::rel_ops; // operators >, >=, <=, ! are "magically" defined! }; (I just invented the term "lessality" for analogy purposes, my head refuses to come up with the correct mathematical term for some reason...) I created a simple header <step_ops.hpp> whose content somewhat imitates the std::rel_ops namespace found in the Utility header. Fro what I can see after a couple of compiles, it just works(TM). Can I / Should I use this trick? What are possible pitfalls I could come up against if I create a class and use a using namespace MyLibrary::increment_operators (for example)? And maybe much, MUCH more important: Have I just reinvented the wheel again, or have I just created a useful small library that could be aggregated to such kinds of projects? Pretty much any experiments that I have tried to do with C++ to get myself back up-to-speed and collaborate stuff seem to already be covered under a boost::do_something facility and it makes me kind of sad that I have spent so much time away.
Boost provides this functionality in the Boost Operators utility library. Its implementation is a little different, but achieves the same result. Can I / Should I use this trick? Use it wherever you can; cutting out redundant and repetitive code is a fundamental principle of refactoring and is a good practice to get into. Have I just reinvented the wheel again, or have I just created a useful small library that could be aggregated to such kinds of projects? I guess you could say then that you've reinvented the wheel. I don't think that's necessarily a bad thing, though: I find that if I implement something myself I usually understand it much better and learn a lot through the process.
3,242,662
3,247,502
fftw3 on windows 64-bit
I would like to use FFTW3 on Windows-64 bit. I follow the instructions on FFTW website: download the package, unzip, run lib.exe to create .lib "import libraries". After doing so, I build my application (which runs just fine using FFTW3 dlls 32-bit) and I get the following errors: 1>pyramidTransform.obj : error LNK2019: unresolved external symbol __imp_fftw_destroy_plan referenced in function "int __cdecl fourier2spatialband1(int,int,float *,float ,double ()[2],double ()[2],double ()[2])" (?fourier2spatialband1@@YAHHHPEAM0PEAY01N11@Z) 1>pyramidTransform.obj : error LNK2019: unresolved external symbol __imp_fftw_execute referenced in function "int __cdecl fourier2spatialband1(int,int,float *,float ,double ()[2],double ()[2],double ()[2])" (?fourier2spatialband1@@YAHHHPEAM0PEAY01N11@Z) 1>pyramidTransform.obj : error LNK2019: unresolved external symbol __imp_fftw_plan_dft_2d referenced in function "int __cdecl fourier2spatialband1(int,int,float *,float ,double ()[2],double ()[2],double ()[2])" (?fourier2spatialband1@@YAHHHPEAM0PEAY01N11@Z) 1>pyramidTransform.obj : error LNK2019: unresolved external symbol __imp_fftw_free referenced in function "int __cdecl decompose(int,int,float *,int,int,float * *,float * *,float *,float * * *,float * * *,float * *,float * *)" (?decompose@@YAHHHPEAMHHPEAPEAM10PEAPEAPEAM211@Z) 1>pyramidTransform.obj : error LNK2019: unresolved external symbol __imp_fftw_malloc referenced in function "int __cdecl decompose(int,int,float *,int,int,float * *,float * *,float *,float * * *,float * * *,float * *,float * *)" (?decompose@@YAHHHPEAMHHPEAPEAM10PEAPEAPEAM211@Z) The property pane for Additional Dependencies clearly shows that I am linking to libfftw3-3.lib (created above). How can I tell what Visual Studio trying to link to? Has anyone have any luck with FFTW-3 in Windows 64-bit?
I found the problem. With FFTW3, since the authors have already compiled the DLLs for Windows, you need to create import libraries (.lib) files from the supplied .def files. You do so by going to the Visual Studio 2008 command prompt: lib /def:libfftw3-3.def Microsoft (R) Library Manager Version 9.00.21022.08 Copyright (C) Microsoft Corporation. All rights reserved. LINK : warning LNK4068: /MACHINE not specified; defaulting to X64 Creating library libfftw3f-3.lib and object libfftw3f-3.exp The problem was that I must have started the wrong command prompt when I first created these .lib files. More instructions can be found at FFTW Windows website. It is also important to note that if you're following the steps from the above website, you're gonna need to run the commands from a folder that doesn't require administrator privileges. By doing this, you'll be able to get your .lib files. Then, you just copy them into the VS lib folder and you're ready to go.
3,242,768
3,246,143
Purging Preprocessing Macros
This is an odd problem, so I have to provide a bit of background. I have a C++ project that I'm working on that I want to clean up a bit. The main issue that I'm dealing with that makes me want to barf is the massive abuse of preprocessor macros that are used in a core component of the project. There's a file with a bunch of #defines that are commented/uncommented before compiling and using the program in order to toggle the use of different algorithms. I'd much rather have command-line arguments to do that rather than recompiling every time we want to try a different algorithm. The problem is that there are so many #ifdef's interwoven throughout the code that it seems impossible to simply refactor the code for each algorithm. I've been told that the reasoning behind this is that this is supposed to be a real-time system that will be dealing with millisecond units of time, and the code in this component is called so many times that having an if check would adversely affect our performance. If you want to try another algorithm, you have to set the appropriate flags and recompile so that performance is optimized. So my question for you all is this: Is there any way that I can get rid of these macros and instead use command-line arguments without a heavy hit to performance and without reworking the logic and the code? One of the options I was considering was trying to have compiled versions of this component for each of the possible combinations of algorithms, and then pick the version that would be defined by the combination of provided command-line arguments. But according to my friend, the number of combinations is just too many for this to be feasible. I haven't worked out the numbers myself, but I'll take his word for it considering how much work he put into this code.
this is supposed to be a real-time system that will be dealing with millisecond units of time That's a real problem. [...] that having an if check would adversely affect our performance. That's not a good reason. If your code has been benchmarked for performance and optimized as a result (as it should have been), that would apply. I can't imagine any scenario where you would obtain a significant performance gain by replacing ifs with #defines (unless the ifs were done comparing string contents, using sequential search, or something similarly disastrous on performance). Because of this I'm willing to bet that the decision to use macros was chosen at design time which would probably make it a case of premature optimization ("premature optimization is the root of all macro-definitions" :D) Is there any way that I can get rid of these macros and instead use command-line arguments without a heavy hit to performance and without reworking the logic and the code? Yes. Here are some possible steps (there are other solutions, but this one is not using ifs at all: Define a benchmark on your code and run it (store the results) Locate one area of the code that's implemented in terms of more than one possible #defines. Move the defines behind functions with a common interface. At run-time, compare a parameter to a constant and pass a pointer to the chosen function to the client code. Things to avoid: performing the comparison more than once; after the comparison you should have a chosen function pointer; that function pointer should be passed around, not your parameter. performing the comparison using strings (or char* or anything that's not a number). Comparing strings - or any comparision not done in constant time - is disastrous for performance-critical code. Instead of comparing the parameter value using an if consider doing it using a switch statement. passing large structures as parameters to your strategy functions. Passing should be done by (const) references or by pointers. call the strategy code through the function pointer instead of directly. Repeat benchmark done at step 0 and compare performance. At this point you should have a strong case to present to your boss/manager: you can make the code run as fast (adding the cost of a function call to your performance-critical code shouldn't matter much - at assembly level a function call should involve passing a few pointers on the stack and a jmp instruction - I think). You can show it runs as fast using your benchmark results. you code will be easier to maintain (more modular, separating functional blocks behind interfaces, centralizing change and so on) your code should be easier to extend (same reasons as above) you should not have to recompile your codebase any longer. you got rid of a big problem (caused by premature optimization). you can continue to refactor the code base (and get rid of more macros) as development/maintenance goes on in other areas, with virtually no changes in functional behavior.
3,242,897
3,245,221
Can I configure Visual Studio to use real folders instead of filters in C++ projects?
It's annoying to have to separately maintain a .filters file to make Visual Studio happy, as well as my project's on-disk layout. Is it possible to tell VS to use real folders, like it does for C#?
In the Solution Explorer in Visual Studio, just click the toolbar button called 'Show All Files'. That does exactly what you want. EDIT(Billy O'Neal): Added image for others so they don't have to hunt... (source: billy-oneal.com)
3,243,146
3,243,284
Why does this EXC_BAD_ACCESS happen with long long and not with int?
I've run into a EXC_BAD_ACCESS with a piece of code that deals with data serialization. The code only fails on device (iPhone) and not on simulator. It also fails only on certain data types. Here is a test code that reproduces the problem: template <typename T> void test_alignment() { // allocate memory and record the original address unsigned char *origin; unsigned char *tmp = (unsigned char*)malloc(sizeof(unsigned short) + sizeof(T)); origin = tmp; // push data with size of 2 bytes *((unsigned short*)tmp) = 1; tmp += sizeof(unsigned short); // attempt to push data of type T *((T*)tmp) = (T)1; // free the memory free(origin); } static void test_alignments() { test_alignment<bool>(); test_alignment<wchar_t>(); test_alignment<short>(); test_alignment<int>(); test_alignment<long>(); test_alignment<long long>(); // fails on iPhone device test_alignment<float>(); test_alignment<double>(); // fails on iPhone device test_alignment<long double>(); // fails on iPhone device test_alignment<void*>(); } Guessing that it must be a memory alignment issue, I decided I want to understand the problem thoroughly. From my (limited) understanding of memory alignment, when tmp gets advanced by 2 bytes, it becomes misaligned for data types whose alignment is greater than 2 bytes: tmp += sizeof(unsigned short); But the test code is executed alright for int and others! It only fails for long long, double and long double. Examining the size and alignment of each data type revealed that the failing data types are the ones that have different sizeof and __alignof values: iPhone 4: bool sizeof = 1 alignof = 1 wchar_t sizeof = 4 alignof = 4 short int sizeof = 2 alignof = 2 int sizeof = 4 alignof = 4 long int sizeof = 4 alignof = 4 long long int sizeof = 8 alignof = 4 // 8 <> 4 float sizeof = 4 alignof = 4 double sizeof = 8 alignof = 4 // 8 <> 4 long double sizeof = 8 alignof = 4 // 8 <> 4 void* sizeof = 4 alignof = 4 iPhone Simulator on Mac OS X 10.6: bool sizeof = 1 alignof = 1 wchar_t sizeof = 4 alignof = 4 short int sizeof = 2 alignof = 2 int sizeof = 4 alignof = 4 long int sizeof = 4 alignof = 4 long long int sizeof = 8 alignof = 8 float sizeof = 4 alignof = 4 double sizeof = 8 alignof = 8 long double sizeof = 16 alignof = 16 void* sizeof = 4 alignof = 4 (These are the result of running the print function from "C++ data alignment and portability") Can someone enlighten me what's causing the error? Is the difference really the cause of EXC_BAD_ACCESS? If so, by what mechanics?
That's actually very annoying, but not so unexpected for those of us bought up in a pre-x86 world :-) The only reason that comes to mind (and this is pure speculation) is that the compiler is "fixing" your code to ensure that the data types are aligned correctly but the sizeof/alignof mismatches are causing problems. I seem to recall that ARM6 architecture relaxed some of the rules for some data types but never got a good look at it because the decision was made to go with a different CPU. (Update: this is actually controlled by a register setting (hence probably the software) so I guess even modern CPUs can still complain bitterly about the misalignments). The first thing I would do would be to have a look at the generated assembly to see if the compiler is padding your short to align the next (actual) data type (that would be impressive) or (more likely) pre-padding the actual data type before writing it. Secondly, find out what the actual alignment requirement are for the Cortex A8 which I think is the core used in the IPhone4. Two possible solutions: 1/ You may have to cast each type into a char array and transfer the characters one at a time - this should hopefully avoid the alignment issues but may have a performance impact. Use of memcpy would probably be best since it will no doubt be coded to take advantage of the underlying CPU already (such as transferring four-byte chunks where possible with one-byte chunks at the start and end). 2/ For those data types that don't want to be put immediately after a short, add enough padding after that short to ensure they align correctly. For example, something like: tmp += sizeof(unsigned short); tmp = (tmp + sizeof(T)) % alignof(T); which should advance tmp to the next properly aligned location before attempting to store the value. You'll need to do the same reading it back later (I'm assuming the short is indicative of the data being stored so you can tell what data type it is). Putting the final solution from OP in the answer for completeness (so people don't have to check the comments): First, the assembly (on Xcode, Run menu > Debugger Display > Source and Disassembly) shows that the STMIA instruction is used when handling 8 bytes of data (i.e., long long), instead of the STR instruction. Next, section "A3.2.1 Unaligned data access" of the "ARM Architecture Reference Manual ARMv7-A" (the architecture corresponding to Cortex A8) states that STMIA does not support unaligned data access while STR does (depending on certain registry settings). So, the problem was the size of long long and misalignment. As for the solution, one-char-at-a-time is working, as a starter.
3,243,240
3,245,670
Uninstall a J2ME application through J2ME code?
Is there any way to do this? I found some Symbian C++ codes that could do it but nothing in J2ME. I have a J2ME certificate and don't have Symbian C++ certificate. Thanks in advance, Ashish.
Unless the device manufacturer has extensions to allow this, it is not possible to uninstall JavaME midlets from JavaME code.
3,243,401
3,243,479
Passing objects and object oriented design best practices
I'm a university student learning programming. For practice I'm writing a blackjack program. I'm using C++ and doing an object oriented approach to this. I have a Deck class designed that basically builds and shuffles a deck of cards. The deck generated is composed of an array of 52 Card class objects. That's what I have so far. My plan is to have a Dealer object, which has a Deck of 52 Cards deal a Card to a second Player object and then deal to the Dealer's own hand. My first question is: Is it bad practice to make the array of Card objects public in the Deck class? I ask this because I consider the array an attribute and was taught that most attributes should be made private. I don't want to start using bad or lazy practices in my projects and want to do it the right way. Another question: How are objects, such as the Card object used in my blackjack program, generally moved from within an object -like the dealer- to a second object like a player?
My first question is: Is it bad practice to make the array of Card objects public in the Deck class? Yes. In general, data members should always be private. It is good OOP to create an interface with no associated data that defines what operations can be performed on the object, and then to provide a concrete class that implements that interface. The data is an implementation detail that should not be visible in the interface or even in the fully concrete class. As an example of why it is bad, you might implement your class using an array of Card objects right now, but maybe later you decide to use a bitset where a single bit indicates whether the card is or isn't present in the deck. If you make your Card array object public, changing the representation in that manner would break other users of your class; however, if you keep it private, you can make that change without impacting the users of your class. Another question: How are objects, such as the Card object used in my blackjack program, generally moved from within an object -like the dealer- to a second object like a player? It depends on whether the other object needs to access the original card object, whether the other object will hold onto the original object for a long time or only a short time, or if the other object is able to handle only a copy of the card. It also depends on whether the card is a concrete class or a polymorphic type, since polymorphic objects can only be passed by pointer or reference (because passing polymorphic objects by value will lead to code slicing). With concrete objects, you have the option to pass a copy unless you need to modify or access the original object, in which case a reference is needed. Choosing the right way to pass objects is somewhat complicated, but hopefully this will clarify: Pass by value if: It is a primitive type or small, non-polymorphic concrete type that does not need to be modified. Pass by constant reference -- that is const T& for some type T -- if: You do not need to modify the original object. You do not need to read the original object outside of the scope of the function. You do not need to read the object beyond the scope of the function, or the type is non-polymorphic and cheap to copy, so you can create a copy if you need to hang onto it. Pass by reference -- that is T& for some type T -- if: You need to modify the original object. You do not need to read/write the original object outside of the scope of the function. You do not need to read the object beyond the scope of the function, or the type is non-polymorphic and cheap to copy, so you can create a copy if you need to hang onto it. Pass by constant smart pointer to a const -- that is const shared_ptr<const T>& for some type T -- if: You need to read the original object both in the scope of the function and beyond. You need to read the object both in the scope of the function and beyond, and the type is non-polymorphic so that it is not possible to safely create a copy of it. Pass by constant smart pointer -- that is const shared_ptr<T>& for some type T -- if: You need to read and write the orginal object both in the scope of the function and beyond. I have given each of the above in deliberate order; you should try the first one that will suffice for the job, only moving onto the next if the previous is not sufficient. Also, I should add that boost::call_traits<T>::param_type can help you choose between passing by value and passing by constant reference in the case of concrete non-polymorphic types (it can determine, based on the size of the object, whether pass by value or pass by constant reference is better).
3,243,454
3,243,463
What is the Linux equivalent to MAXDWORD?
In Microsoft Visual C++, there is a constant called MAXDWORD defined in winnt.h as follows: #define MAXDWORD 0xffffffff It's useful as a high initial value for a 'double' when one is searching for the lowest value in a collection. Google though I might, I can't find the equivalent in standard headers on Linux, but I'm willing to bet there must be one. I'm using: uBuntu 10.04 64bit g++ 4.4.3
Standard solution is to use std::numeric_limits. For instance, std::numeric_limits<long>::max(). You could use any standard type instead of long there. You even can to specialize numeric_limits for custom types.
3,243,581
3,243,674
Using getenv function in Linux
I have this following simple program: int main() { char* v = getenv("TEST_VAR"); cout << "v = " << (v==NULL ? "NULL" : v) << endl; return 0; } These lines are added to .bashrc file: TEST_VAR="2" export TEST_VAR Now, when I run this program from the terminal window (Ubuntu 10.04), it prints v = 2. If I run the program by another way: using launcher or from Eclipse, it prints NULL. I think this is because TEST_VAR is defined only inside bash shell. How can I create persistent Linux environment variable, which is accessible in any case?
On my system (Fedora 13) you can make system wide environment variables by adding them under /etc/profile.d/. So for example if you add this to a file in /etc/profile.d/my_system_wide.sh SYSTEM_WIDE="system wide" export SYSTEM_WIDE and then open a another terminal it should source it regardless of who the user is opening the terminal echo $SYSTEM_WIDE system_wide
3,243,649
3,255,124
Dependency injection: do we all need to know that?
One of my friend (he is a .NET/C++ developer, as I am) asked me: Dependency injection: do we all need to know that? Why? Could you please tell: Your opinion: do we really need to know that pattern and how to implement it? Good reference (link) that could explain "why?" Thank you a lot. P.S. I am understanding that I am asking a lot... but I can't find good reference myself...
Good comments are posted here, but there are no clear answer on the question "Your opinion: do we really need to know that pattern and how to implement it?" From my perspective it should be "yes" if at least one of option is applied to you: you need to write (automated) unit-tests for application; you need to decouple components of your application; you want to have ability to easily change source of data. Answer on question "Why?" are listed in suggested links. Many thanks for your help.
3,243,711
3,243,776
Member function cannot access private member
I have got the following code #include <iostream> #include <string> template <typename T> class demo { T data; public: demo(); demo(demo const&k ); demo(const T&k); demo& operator=(const demo &k); template<typename T1> demo(const demo<T1>&k); template<typename T1> demo<T>& operator=(const demo<T1>&k); ~demo(); }; template <typename T> demo<T>::demo():data(){} template<typename T> demo<T>::demo(demo const& k):data(k.data){} template<typename T> demo<T>::demo(const T&k):data(k){} template<typename T> demo<T>& demo<T>::operator=(demo const &k) { if ((void*)this == (void*)&k) { // assignment to itself? return *this; } this->data=k.data; return *this; } template<typename T> template<typename T1> demo<T>& demo<T>::operator=(demo<T1> const &k) { if ((void*)this == (void*)&k) { // assignment to itself? return *this; } this->data=k.data; return *this; } template<typename T> template<typename T1> demo<T>::demo(const demo<T1>&k):data(k.data){} template<typename T> demo<T>::~demo(){} int main() { demo<std::string> k(std::string("hello")); demo<std::string >l=k; demo<int> x(10); demo<double> p=x; //error here } Why do I get error here? As far as I know p is being copy initialized to x. So demo<T>::demo(const demo<T1>&k):data(k.data){} is invoked. But since data is a private member I get an error 'demo<T>::data' : cannot access private member declared in class 'demo<T>'. Why? I know that member functions of a class can access private members , so why do I get an error? What should I do to correct the error?
Because demo<T> and demo<T1> are considered different types they may not access each other's private data. Easist way to solve this is by adding a public accessor function and using it: template <typename T> class demo { public: const T &get_data() const { return data; } ... }; template<typename T> template<typename T1> demo<T>::demo(const demo<T1>&k):data(k.get_data()){}
3,244,269
3,244,285
C++ : How expensive is ofstream.tellp()?
I want to call it in a tight loop thousands of times per second . Is it an expensive call? I am using Windows Visual C++ .
C++ doesn't mandate the performance (in seconds) of any particular parts of that standard library (although many containers and algorithms have complexity requirements). This means that you are at the mercy of your implementation. The only reliable thing to do is to measure it and see if it is acceptable in your application.
3,244,681
3,286,966
How to get the Last Active Date of a Process?
I have an assignment were in I have to print the last active date of the process using a COM In Proc Server in C++. I tried doing that with getProcessTimes() function, but that gives me an access violation error. First of all, I want to know if there is anyother command that gives the last active date of the process.. Second what is the problem with the following code FILETIME ftCreation, ftKernel, ftUser; GetProcessTimes(hProcess, &ftCreation, &ftExit, &ftKernel, &ftUser);` I tried memsetting and several other alternatives but nothing works...
Here is an article that demonstrates how to use GetProcessTimes. It includes sample code. Another option is using WMI and the WIN32_Process class, which also has this information. Here is an example of how you would use WMI.
3,244,741
3,244,980
Need some help writing my results to a file
My application continuously calculates strings and outputs them into a file. This is being run for almost an entire day. But writing to the file is slowing my application. Is there a way I can improve the speed ? Also I want to extend the application so that I can send the results to an another system after some particular amount of time. Thanks & Regards, Mousey
There are several things that may or may not help you, depending on your scenario: Consider using asynchronous I/O, for instance by using Boost.Asio. This way your application does not have to wait for expensive I/O-operations to finish. However, you will have to buffer your generated data in memory, so make sure there is enough available. Consider buffering your strings to a certain size, and then write them to disk (or the network) in big batches. Few big writes are usually faster than many small ones. If you want to make it really good C++, meaning STL-comliant, make your algorithm a template-function that takes and output-iterator as argument. This way you can easily have it write to files, the network, memory or the console by providing appropriate iterators.
3,244,760
3,246,629
How to get all duplicate symbol linker errors at once?
I am building a C++ project in XCode which uses two libraries. Say for e.g libX.a and libY.a. There are some function definitions common on libX.a and libY.a for which I get duplicate symbol linker error. This is fine, but I get only one error at a time. Once I fix the error, I'll get the next duplicate symbol error and this process repeats. I have two problems with this approach: I don't have an exact count of the number of duplicate errors. I wanted to know all the duplicate symbols found. So that I can distribute the fixing of this between couple of developers. Fixing the error is fast enough compare to the time it takes to build the libraries and then link to generate the executable. Is this possible? I mean is it possible by setting any flag so that the linker gives all the duplicate symbols at once. EDIT: adding sample code for clarification: Let me show an example here: test1.h void foo() { } void bar() { } test2.h void foo() { } void bar() { } test1.cpp #include "test1.h" void j() { foo(); bar(); } test2.cpp #include "test2.h" void k() { foo(); bar(); } Compiling now: g++ -c test1.cpp g++ -c test2.cpp Linking now: g++ -o final test1.o test2.o Even though there are 2 duplicate symbols foo and bar, I get the error only for foo as shown below: ld: duplicate symbol foo() in test2.o and test1.o collect2: ld returned 1 exit status Once I fix foo, then I get the error for bar shown below: ld: duplicate symbol bar() in test2.o and test1.o collect2: ld returned 1 exit status What I would like is getting these two errors at once. So that I fix all of them and then link at one shot. Thanks Best Regards, Marc
You can use the nm command to list all the symbols in the libraries, and sort and uniq -d to print the duplicates. Something like: nm -j test1.o test2.o | sort | uniq -d This will also list the undefined symbols they share in common. You can get a list of those with nm -u. A bit of a hack, but it might get you there faster.
3,245,048
3,247,607
(student) interview questions - programming for a robotics lab
my robotics lab is looking for programmers to work on some projects we have at the moment. We nailed down the requirements (mainly, c++ and experience with openGL and 3D), but due to obvious money constraints we can't afford to hire Great Developers. Instead we're going to settle for Talented Students, offering them projects for their dissertation/thesis and hoping for some fresh ideas and creativity from their side. We can also afford to pay students that just graduated (first job experience). So my question is: In your experience, how did you spot a Talented Student (computer scientist or engineer)? What questions did you ask? What else did help you in finding a candidate that turned out to be a Good Programmer? (note: they might not know much about a specific language, but might have the ability to learn pretty fast) or, if you were the interviewee, Which questions were asked that made you jump on the bandwagon? Or, if you had an awful experience, what - in retrospect - was an obvious warning signal that you ignored? Please note that I am not looking for an argumentative answer. We can talk all day long about what's best for us and never agree. Instead, I'm looking for tales from your experience. Anecdotes, stories, hints, everything will help. Background: A bit more background: working for academia here is slightly different than working for the private sector (here = Italy). There are no 'deadlines' to 'sell' a product; instead, it's all proof-of-concept based. Nothing you start working on has the guarantee to be functional. A comic best describes it: reinventing the wheel I am considering doing Coding Questions for their interview, but all my colleagues are scoffing at me (too scary, nobody will ever come to work for us again, nobody really know how to code, etc). Coding-wise, programming done by researchers is ... ugly. I am fighting to get a version control system in constant use, people have to be chased down to report bugs and document their code, everything is coded-so-that-it-works and rarely we go back to old code to 'fix bugs'. Basically once it's somewhat working, the project is closed and people go work on another project. Lots has been reinvented and rewritten over and over again (just because nobody knew it was already there). People come and go, future is uncertain, but we play with robots so it's very cool :) Furthermore, being really understaffed, nobody can follow you and guide you in your project. At best you're the one that has to come up with a plan, background literature and a working prototype. Hence, we are looking for people that: have some background to get started can be highly independent do want to learn and build their own expertise in new fields
Actually, here's my best advice: Recruit among your students. Since you work for an academic institution I assume that either you or your colleagues teach. This provides you with a wealth of information about what potential recruits are capable of -- how fast they learn, how motivated they are, what they are good and bad at, how the code they turn in for the lab assignments and projects look like, etc.
3,245,099
3,245,143
Overloading operator<< to work for string
In the following code: using namespace std; //ostream& operator<< (ostream& out,const string & str) //{ // out << str.c_str(); // return out; //} int _tmain(int argc, _TCHAR* argv[]) { ofstream file("file.out"); vector<string> test(2); test[0] = "str1"; test[1] = "str2"; ostream_iterator<string> sIt(file); copy(test.begin(), test.end(), sIt); file.close(); return 0; } what is the proper way to overload operator << to make copy(test.begin(), test.end(), sIt); work. What am I missing? EDIT: I'm just stupid... forgot to include "string" header Thank you!
You do not need to overload operator<< to work with strings, it already knows how to handle them. std::copy( test.begin(), test.end(), std::ostream_iterator<std::string>( file, "\n" ) ); will produce: str1 str2 Is there anything different/special that you want to be done there?
3,245,148
3,245,163
C++ template question
Is there any way to achieve the specified behaviour? If there is some trick or this could be done using traits or enable_if, please let me know. template <typename T> struct Functional { T operator()() const { T a(5); // I want this statement to be tranformed into // plain 'return;' in case T = void return a; // <--- } }; int main() { Functional<int> a; a(); Functional<void> b; b(); // <--- Compilation error here }
Just specialize for void: template <typename T> struct Functional { T operator()() const { T a(5); return a; } }; template <> struct Functional<void> { void operator()() const { } };
3,245,310
3,245,611
C++ Boost function comparison
I have a class which contains boost::function as one of its arguments. I have to make this class equality comparable but the boost::function is not equality comparable. Is there a easy workaround for this problem? Thanks, Gokul.
boost::function is not eq_compare because there is good way to handle the fact that many functors are not eq_compare. Here is a bit of insight into it: http://www.boost.org/doc/libs/1_35_0/doc/html/function/faq.html#id690470 Unfortunately, the boosties decided not to provide a policy-based approach which would allow us to select the alternative, i.e. "eq-comparable functors only or bust" implementation, leaving us a bit stuffed here. There might be a couple of crappy workarounds for this situation but I'd suggest to either: ditch boost::function altogether and roll your own if you really,really need this eq_comparable thing. or See if your problem can be solved in a very different way. For example many people use function<> to implement a kind of event system. If that's the case, then you should have a look at boost::signals.
3,245,321
3,245,361
C++ variant for Java long?
Is there a C++ variant for the long primitive data-type? A C++ long is only 4 bytes, while a Java long is 8 bytes. So: Is there a non-decimal primitive type with a size of 8 bytes in C++? Maybe with some tricks? Thanks
Microsoft Visual C++ defines an __int64 type that's equivalent to Java's long. gcc has int64_t. There's even a long long int type defined in the ISO C99 standard, however according to the standard it's at least 64 bits wide, but could be wider. But apart from the size, there's also endianness to consider. The Java standard mandates big endian, but with C, endianness is AFAIK always platform-dependant.
3,245,387
3,246,947
Automatically generate a locale csv file for Excel in C++
I want to generate a csv file containing numbers and I want Excel to read that file automatically. However, Excel uses a different csv format depending on the locale settings. For example: English: Text separator: , Decimal separator: . Spanish: Text separator: ; Decimal separator: , Is it possible to automatically detect those settings in C++ so I can generate the file according to them? I know I can obtain the decimal separator using a locale object, but I do not know how to obtain the text separator. This question is related to: CSV is actually … Semicolon Separated Values . However, I do not want to read the file but to generate it and I want to automatically detect the settings.
I don't think that standard C++ has a notion of "text separator", and that this is Windows-specific. You could thus use GetLocaleInfo with the LOCALE_SLIST flag.
3,245,405
3,245,903
Embedding a Prolog engine in Obj-C projects
I'm looking for a light-weight Prolog engine to be embedded in an Obj-C application under Mac OSX. In Java there are some excellent implementations with the characteristics I need: deployability, lightness, dynamic configurability, integration with Java and ease of interoperability. Can you recommend something similar in C/C++? After several searches I found YAProlog and reading here it seems it can be used as library to be called from other programs. But (stupid questions): I'm inexperienced with UNIX and I don't know exactly how to produce libyap.a file with those commands of the YAP manual... Can I then copy libyap.a in my Xcode project and use it?
GProlog supports Mac OS X (Darwin) and there's an installer for Mac OS X Leopard. And here you can read how to call gprolog from C (read also this). Then instead of using gplc, you can use gcc provided that you add the proper options for linking, which could be a bit "trickie" to be found; so you can produce object files with gplc and then glue everything together... About YAP: 1) Usually package with autoconf are compiled simply with the following "sequence" of commands ./configure make A final make install should install everything and must be executed by a user having the rights to do so. The manual suggest the creation of an ARCH (ARCH.?) dir and doing everything from there (so, ../configure instead of ./configure). The configure script accepts usually options, take a look at them. Check in particular where are LIBDIR and YAPLIBDIR. So, once you have the source tarball (the .tar.gz of the source), you should dearchive it, a command like tar -xzf Yap-5.1.3.tar.gz works on GNU/Linux and the same tar should be also on Mac OS X... Let's look at ./configure --help and look if you see interesting option you want to use before proceeding. Now, let's follow manual's suggestion (even if it looks odd to me;-)) mkdir ARCH. # I would put GNUlinux, or maybe # the name must be exactly this? cd ARCH. ../configure You wait... and the directory gets populated of evrything needed for the next step. Take a look at the created Makefile, you see lines like # # where YAP should look for binary libraries # LIBDIR=$(EROOTDIR)/lib YAPLIBDIR=$(EROOTDIR)/lib/Yap Among the targets of the Makefile, I can read also libYap.a. So, try the make (I won't do that to check what can go wrong, also because I am on GNU/Linux and how I can solve problems could be different), at the end, you should obtain the libYap.a, and so, become "root" (administrator) and do make install In the install target (exactly install_unix for me) I read $(INSTALL_DATA) -m 755 libYap.a $(DESTDIR)$(LIBDIR) which means that your .a is installed and should be ready to be used by a compiler, provided you know where the lib is (and you know it, see above and remember the configure's options) 2) Of course you can copy it directly where you need it and use it "directly", but since it is "canonically" installed by the make install, use it the way you'd use any other "system wide" lib archive.
3,245,406
3,245,707
Allocating largest buffer without using swap
In C/C++ under Linux, I need to allocate a large (several gigabyte) block of memory, in order to store real-time data from a sensor connected to the ethernet port and streaming data at about 110MB/s. I'd like to allocate the largest amount of memory possible, to maximise the length of data sequence that I can store. However, I also need to make sure that there will be no disk-swapping, since the resulting delay and limited bandwidth of disk access causes the sensor's (very limited) buffer to overflow. What is the best way to determine how much memory to allocate? Am I limited to just allocating a slightly smaller block than the reported free memory, or can I interface more directly with the linux virtual memory manager?
Well, under linux you can use mlock()/mlockall() to keep an adress range in physical memory and prevent it from being swapped out. The process using mlock needs a couple of privileges to do so, "man mlock" has the details. I am not sure about the maximum mlock'able block (it might differ from what seems to be "free"), so probably a binary search could help (lock a range, if that fails reduce the size of the area etc..) On the other hand, 110MB/s is not really a problem for a Solid-State-Drive. A 60GB SSD with 280MB/s write speed costs about $200 on the corner. Just copy the sensor data into a small write buffer and stream that to the SSD.
3,245,518
3,245,534
Calling delete on two pointers to the same object
I'm having a problem with a couple of event handler classes I'm trying to write. Basically, the idea is to have an event handler class for each logical group of objects. In most cases, the events are between objects and their handler, but in some cases events are also sent between handler objects as well. I've written the code such that the events are placed on a stack (stack as in user created structure; the events themselves are allocated using new) and deleted after their information is read and acted upon. This is giving me some problems because in one case, the event is sent along a chain of three handlers. Say, HandlerA sends a new Event to HandlerB, which places it on the stack and reads it, sending it to HandlerC, which reads it and performs whatever it needs to perform, after which it deletes the Event pointer and sets it to NULL. Now, we pop back to HandlerB and, well, it also wants to delete and NULL the pointer to the event. But the pointer is a local variable, and it ends up deleting the same address twice, giving an exception. How do you go around this? Do you need to use one of those fancy auto_ptrs (still an early learner here), or am I missing something fundamental here?
I've written the code such that the events are placed on a stack and deleted after their information is read and acted upon. There is some confusion here - objects on the stack should not be deleted. Objects created with new (on the heap) should. In general, you should define a clear ownership strategy for your objects on the heap. Each object should have one owner, and it should be clear who the owner is at any point in time. That owner - and it alone - shall delete the object. You may also want to use boost::shared_ptr (it may be available also as std::tr1::shared_ptr, depending on your compiler) instead of raw pointers. This keeps count of the references to the object, and deletes it when the ref count drops to 0.
3,245,552
3,245,576
Why is Erlang said to be more suited for server side programming in webgames than Java and C++?
I don't really understand, how can Erlang be more efficient than C++?
Erlang is far less efficient than C++. Erlang's big strength is scalability, not efficiency. It will linearly scale across multiple CPUs and, due to its programming and communications model, will very easily scale across machine clusters. Just to be clear, Erlang won't scale more than C++; it just scales more easily than C++. A lot more easily. See chapters 5 and 6 of Concurrent Programming in Erlang for a very good explanation of why this is so.
3,245,914
3,245,990
What field of PE Headers tells that whether a valid PE file or not?
I need to validate whether the given binary is a PE file or not (e.g. if I rename JS/HTML or .class files to .exe or .dll), it won't still be PE files. Parsing PE files would give me info about this problem; what field indicates that a given binary is a valid PE file or not? I have checked the "e_magic" field of FileHeader, it always gets populated in the case of wrong PE files (i.e. js/html/java/class files renamed to .dll/Exe) and doesn't say anything about the validity of the PE.
Check the Portable Executable/Common Object File Format Specification. There are three magic values for you to check: The MZ header's magic number at the beginning of the file The PE header's magic number "PE\0\0" at the start of the PE header Version identifier for the optional header, IIRC, it's 0x10b for PE files, and 0x20b for PE+ (x64) files. Beyond that, you'd have to parse the entire file and look at every processor instruction to ensure it's valid, etc. Several of the files use the COFF spec internally, and you might not have an easy way to distinguish that. PE's format itself was designed with multiple machines, and many different forms of compiled code can be contained while keeping the file valid.
3,245,955
3,245,970
Defining constants inside a structure
Is there any special significance to defining constant data inside a structure as shown. This is from a 3rd party library. typedef struct { IntVB abc_number; #define ABC_A 0x01 #define ADBC_E 0x02 IntVB asset; } StructA;
Not really. They probably provide better significance to the programmer in that spot of the code. Meaning that those constants are probably related to the items in that struct container, or to the behavior of the struct.
3,246,161
3,246,241
C++ optimization question
I have some mid-large project that is actively using boost libraries and, hence, suffers in terms of Debug application performance (Visual Studio 2008). Solution that I use right now means turning on function inlining even in Debug mode, which brings enough performance, but should definitely have some drawbacks. Does anyone know what will I lose in terms of debugging capabilities if I force function inlining (/Ob2) switch? Maybe someone have any other ideas about speeding up boost / other template libraries Debug performance?
In my opinion, you should probably not be performance-testing your debug release. Save the debug release for unit testing so you can easily find problems but real testing (functionality and performance) should probably be on the release version. That's what your customers will be running after all, right?
3,246,380
3,246,972
On the use (and usefulness) of a pointer to member function vs directly calling the member function
I am new to pointer to member functions, and I would like to know their pros and cons. Specifically, consider this: #include <iostream> #include <list> using namespace std; class VariableContainer; class Variable { public: Variable (int v) : value (v), cb_pointer (0) {} ~Variable () {} void SetCallback (void (VariableContainer::*cb)(int)) { cb_pointer = cb; } void FireCallback (void) { /* I need a reference to a VariableContainer object! */ } private: int value; void (VariableContainer::*cb_pointer) (int); }; class VariableContainer { public: VariableContainer () {} ~VariableContainer () {} void AddVar (Variable &v) { v.SetCallback (&VariableContainer::Callback); } void Callback (int v) { cout << v << endl; } }; int main () { Variable v (1); VariableContainer vc; vc.AddVar (v); v.FireCallback(); return 0; } As stated in the comment, to trigger the callback (FireCallback) I need some reference to an existing VariableContainer object, which should be provided as an additional argument of VariableContainer::AddVar (...). Now: Should I use the pointer to member function? Or should I call directly Callback (...) (since I have a pointer to the VariableContainer object)? What are the advantages and drawbacks of each solution? TIA, Jir
Depending on what will vary in the future, you can decide: Other functions will be called by the variable's FireCallback => a pointer-to-mf may be useful, but other mechanisms are more c++ish Only the 'Callback' function is going to be called => stick with calling arg->CallBack() directly. A possible solution to the problem is using an interface layer: this is no more than an implementation of the Observer pattern. This is a little more OO, hence verbose, but the syntax is way easier. class Observer { public: virtual ~Observer(){}; virtual void callback( int v ) = 0; }; // actual implementation class MyCallbackObserver : public Observer { virtual void callback( int v ) { std::cout << v << std::endl; } void some_other_method( int v ) { std::cout << "other " << v ; } }; And your Variable class would have a container full of observers: class Variable { public: std::vector<Observer*> observers; // warning: encapsulation omitted void FireCallback(){ // assuming C++ 0x for( auto it : observers ) { (*it)->Callback( value ); } } If other functions need to be called on the same object, you may introduce a wrapper: class OtherCaller: public Observer { public: MyObserver* obs; virtual void callback( int v ) { obs->some_other_method( v ); } } And add it to the collection: Variable var; MyObserver m; OtherCaller mo; mo.obs = &m; var.observers.push_back(&m); var.observers.push_back(&mo); var.FireCallback();
3,246,441
3,246,623
What does "BUS_ADRALN - Invalid address alignment" error means?
We are on HPUX and my code is in C++. We are getting BUS_ADRALN - Invalid address alignment in our executable on a function call. What does this error means? Same function is working many times then suddenly its giving core dump. in GDB when I try to print the object values it says not in context. Any clue where to check?
You are having a data alignment problem. This is likely caused by trying to read or write through a bad pointer of some kind. A data alignment problem is when the address a pointer is pointing at isn't 'aligned' properly. For example, some architectures (the old Cray 2 for example) require that any attempt to read anything other than a single character from memory only occur through a pointer in which the last 3 bits of the pointer's value are 0. If any of the last 3 bits are 1, the hardware will generate an alignment fault which will result in the kind of problem you're seeing. Most architectures are not nearly so strict, and frequently the required alignment depends on the exact type being accessed. For example, a 32 bit integer might require only the last 2 bits of the pointer to be 0, but a 64 bit float might require the last 3 bits to be 0. Alignment problems are usually caused by the same kinds of problems that would cause a SEGFAULT or segmentation fault. Usually a pointer that isn't initialized. But it could be caused by a bad memory allocator that isn't returning pointers with the proper alignment, or by the result of pointer arithmetic on the pointer when it isn't of the correct type. The system implementation of malloc and/or operator new are almost certainly correct or your program would be crashing way before it currently does. So I think the bad memory allocator is the least likely tree to go barking up. I would check first for an uninitialized pointer and then bad pointer arithmetic. As a side note, the x86 and x86_64 architectures don't have any alignment requirements. But, because of how cache lines work, and for various other reasons, it's often a good idea for performance to align your data on a boundary that's as big as the datatype being stored (i.e. a 4 byte boundary for a 32 bit int).
3,246,462
3,247,752
Dynamic Creation in Qt of QSlider with associated QLCDNumber
I was wondering what's the best way to go about the following scenario? I am dynamically creating QSliders that I wish to link to an associated QLCDNumber for display. The thing is I would like to have tenths available, so I would like to have a conversion between the QSLider and the QLCDNumber to divide by 10. At this point all I keep really is the QSlider, the QLCDNumbers I just create and forgot about. Is there an easy way of doing the conversion and connection without having to keep too much information? Thanks in advance.
This is basically what I ended up using; it seems to work (though it violates the whole object oriented philosophy). signalMapper= new QSignalMapper(this); QObject::connect(tmpSlider, SIGNAL(valueChanged(int)), signalMapper, SLOT(map())); sliderMapper->setMapping(tmpSLider, tmpLCDNumber); QObject::connect(signalMapper, SIGNAL(mapped(QWidget*)), this, SLOT(updateLCD(QWidget*))) ... void MyClass::updateLCD(QWidget* lcdNum){ ((QLCDNumber*)lcdNum)->display(((QSlider*)(signalMapper->mapping(lcdNum)))->value()*.1); }
3,246,528
3,246,543
Is there a better way to initialize an allocated array in C++?
How to write this in another (perhaps shorter) way? Is there a better way to initialize an allocated array in C++? int main(void) { int* a; a = new int[10]; for (int i=0; i < 10; ++i) a[i] = 0; }
int *a =new int[10](); // Value initialization ISO C++ Section 8.5/5 To value-initialize an object of type T means: — if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); — if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized; — if T is an array type, then each element is value-initialized; — otherwise, the object is zero-initialized For differences between the terms zero initialization, value initialization and default initialization, read this
3,246,619
3,247,061
C++ / Objective-C : The two files of a class are called Header and ...?
In languages like C++ or Objective-C a class normally consist of two files. The first is called Header or Interface but what is the "official" name of the other file? In some books it's just called "Codefile" in other "implementation file" or "message file" for Objective-C. Which name is the right name? I need to write a tutorials and I have no idea.
I always refer to them as "header files" and "implementation files".
3,246,712
3,246,979
C++ - pointer passing question
Does somebody have any idead on how to pass boost::shared_ptr - by value or by reference. On my platform (32bit) sizeof(shared_ptr) equals 8 bytes and it looks like I should pass them by reference, but maybe somebody has another opinion / did a profile / something like that?
You can see this in two ways: a boost::shared_ptr is an object (and should be passed by const &). a boost::shared_ptr models a pointer and should be treated as a pointer. Both of them are valid, and the second option will incur the cost of constructing and destructing the additional instance (which shouldn't be a big issue unless you're writing performance-critical code). There are two cases when you should pass by value: when you're not sure that the type of the pointer will remain the same. That is, if you are considering replacing the shared_ptr<T> with T* in your codebase somewhere in the future, it makes sense to write typedef shared_ptr<T> TPtr; and define your functions as void yourfunction(TPtr value) In this case, when you change the pointer type you will only have to modify the typedef line. when you are sharing a pointer between two modules with a different lifetime. In that case, you need to make sure you have two instances of the smart pointer, and that both increment the reference count of the pointer. In other cases, it's a matter of preference (unless you're writing performance-critical code in which case different rules apply).
3,246,761
3,246,795
Protected vs Private Destructor
Is there any difference between a protected and a private destructor in C++? If a base classes destructor is private, I imagine that it is still called when deleting the derived class object.
Taken from here: If the constructor/destructor is declared as private, then the class cannot be instantiated. This is true, however it can be instantiated from another method in the class. Similarly, if the destructor is private, then the object can only be deleted from inside the class as well. Also, it prevents the class from being inherited (or at least, prevent the inherited class from being instantiated/destroyed at all).
3,246,803
3,247,093
Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?
I have always seen people write class.h #ifndef CLASS_H #define CLASS_H //blah blah blah #endif The question is, why don't they also do that for the .cpp file that contain definitions for class functions? Let's say I have main.cpp, and main.cpp includes class.h. The class.h file does not include anything, so how does main.cpp know what is in the class.cpp?
First, to address your first inquiry: When you see this in .h file: #ifndef FILE_H #define FILE_H /* ... Declarations etc here ... */ #endif This is a preprocessor technique of preventing a header file from being included multiple times, which can be problematic for various reasons. During compilation of your project, each .cpp file (usually) is compiled. In simple terms, this means the compiler will take your .cpp file, open any files #included by it, concatenate them all into one massive text file, and then perform syntax analysis and finally it will convert it to some intermediate code, optimize/perform other tasks, and finally generate the assembly output for the target architecture. Because of this, if a file is #included multiple times under one .cpp file, the compiler will append its file contents twice, so if there are definitions within that file, you will get a compiler error telling you that you redefined a variable. When the file is processed by the preprocessor step in the compilation process, the first time its contents are reached the first two lines will check if FILE_H has been defined for the preprocessor. If not, it will define FILE_H and continue processing the code between it and the #endif directive. The next time that file's contents are seen by the preprocessor, the check against FILE_H will be false, so it will immediately scan down to the #endif and continue after it. This prevents redefinition errors. And to address your second concern: In C++ programming as a general practice we separate development into two file types. One is with an extension of .h and we call this a "header file." They usually provide a declaration of functions, classes, structs, global variables, typedefs, preprocessing macros and definitions, etc. Basically, they just provide you with information about your code. Then we have the .cpp extension which we call a "code file." This will provide definitions for those functions, class members, any struct members that need definitions, global variables, etc. So the .h file declares code, and the .cpp file implements that declaration. For this reason, we generally during compilation compile each .cpp file into an object and then link those objects (because you almost never see one .cpp file include another .cpp file). How these externals are resolved is a job for the linker. When your compiler processes main.cpp, it gets declarations for the code in class.cpp by including class.h. It only needs to know what these functions or variables look like (which is what a declaration gives you). So it compiles your main.cpp file into some object file (call it main.obj). Similarly, class.cpp is compiled into a class.obj file. To produce the final executable, a linker is invoked to link those two object files together. For any unresolved external variables or functions, the compiler will place a stub where the access happens. The linker will then take this stub and look for the code or variable in another listed object file, and if it's found, it combines the code from the two object files into an output file and replaces the stub with the final location of the function or variable. This way, your code in main.cpp can call functions and use variables in class.cpp IF AND ONLY IF THEY ARE DECLARED IN class.h. I hope this was helpful.
3,246,895
3,247,156
Can parentheses take arbitrary identifiers as arguments? C++
For example, is (const int)* someInt; valid code? If so, is that statement different than const int* someInt; ?
You can put arbitrarily many parentheses around expressions without changing the meaning. But you cannot do the same with types. In particular, as the others have pointed out, the parenthese in your code change the meaning from a declaration to a cast.
3,246,917
3,246,946
Can I increase int i by more than one using the i++ syntax?
int fkt(int &i) { return i++; } int main() { int i = 5; printf("%d ", fkt(i)); printf("%d ", fkt(i)); printf("%d ", fkt(i)); } prints '5 6 7 '. Say I want to print '5 7 9 ' like this, is it possible to do it in a similar way without a temporary variable in fkt()? (A temporary variable would marginally decrease efficiency, right?) I.e., something like return i+=2 or return i, i+=2; which both first increases i and then return it, what is not what I need. Thanks EDIT: The main reason, I do it in a function and not outside is because fkt will be a function pointer. The original function will do something else with i. I just feel that using {int temp = i; i+=2; return temp;} does not seem as nice as {return i++;}. I don't care about printf, this is just for illustration of the use of the result. EDIT2: Wow, that appears to be more of a chat here than a traditional board :) Thanks for all the answers. My fkt is actually this. Depending on some condition, I will define get_it as either get_it_1, get_it_2, or get_it_4: unsigned int (*get_it)(char*&); unsigned int get_it_1(char* &s) {return *((unsigned char*) s++);} unsigned int get_it_2(char* &s) {unsigned int tmp = *((unsigned short int*) s); s += 2; return tmp;} unsigned int get_it_4(char* &s) {unsigned int tmp = *((unsigned int*) s); s += 4; return tmp;} For get_it_1, it is so simple... I'll try to give more background in the future...
"A temporary variable would marginally decrease efficiency, right?" Wrong. Have you measured it? Please be aware that ++ only has magical efficiency powers on a PDP-11. On most other processors it's just the same as +=1. Please measure the two to see what the actual differences actually are.
3,247,030
3,247,309
How to customize the display of a QListView
I have implemented a list of users in my Qt program, using the model/view principle of Qt. My QListView displays a subclass of QAbstractListModel and so far this works just fine. Now I would like to customize the display of my user list (display the name on several line, add IP information, and so on: not really relevant, I just want something really custom). I couldn't find anything in the Qt documentation regarding this: what are my options ? Note: The items in the list do not need to (can't) be modified, if this can help. Thank you.
You need to create a new item delegate class to handle the painting. Here is a good answer to a similar question.
3,247,224
3,247,286
C++ friend operator overload doesn't compile
I have the following (cut-down) class definition, and it has compilation errors. #include <iostream> #include <string> class number { public: friend std::ostream &operator << (std::ostream &s, const number &num); friend std::string &operator << (std::string, const number &num); friend std::istream &operator >> (std::istream &s, number &num); friend std::string &operator >> (std::string, number &num); protected: private: void write ( std::ostream &output_target = std::cout) const; void read ( std::istream &input_source = std::cin); void to_string ( std::string &number_text) const; void to_number (const std::string &number_text); }; std::istream & operator >> (std::istream &s, number &num) { num.read (s); return s; } std::string & operator >> (std::string &s, number &num) { num.to_number (s); return s; } std::string & operator << (std::string &s, const number &num) { num.to_string (s); return s; } std::ostream & operator << (std::ostream &s, const number &num) { num.write (s); return s; } When I compile it, I get the following errors... frag.cpp: In function ‘std::string& operator>>(std::string&, number&)’: frag.cpp:17: error: ‘void number::to_number(const std::string&)’ is private frag.cpp:27: error: within this context frag.cpp: In function ‘std::string& operator<<(std::string&, const number&)’: frag.cpp:16: error: ‘void number::to_string(std::string&) const’ is private frag.cpp:32: error: within this context Could anyone help with this; in particular why to_number and to_string are thought private but read and write are OK? Thank you.
The function signatures are different: friend std::string &operator << (std::string, const number &num); friend std::string &operator >> (std::string, number &num); are declared with a string parameter by value, while std::string & operator >> (std::string &s, number &num) ... std::string & operator << (std::string &s, const number &num) ... both have a string& reference parameter. So the function you actually implement is not the same as the one declared as friend - hence the error. Try changing the friend declaration to friend std::string &operator << (std::string&, const number &num); friend std::string &operator >> (std::string&, number &num);
3,247,285
3,247,339
const int = int const?
For example, is int const x = 3; valid code? If so, does it mean the same as const int x = 3; ?
They are both valid code and they are both equivalent. For a pointer type though they are both valid code but not equivalent. Declares 2 ints which are constant: int const x1 = 3; const int x2 = 3; Declares a pointer whose data cannot be changed through the pointer: const int *p = &someInt; Declares a pointer who cannot be changed to point to something else: int * const p = &someInt;
3,247,344
3,266,742
a way to omit taking names for objects that are used only to construct a final object
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 }; suppose the only use of objects of Temp class is to construct objects of Final class, so I wonder if in current standard of c++ , we can using a macro or somehow tell the compiler, since this object of Temp class which I'm defining is only used in one line of code and that is as argument of constructor of Final class; take a name for it yourself so I don't bother myself taking one name for each object Of Temp class?
there's no such thing as I want in current c++ standard, but in upcoming c++0x standard, to initialize an object of the Final class, we can write: Final obj({'a','b'}); So no naming for initializer object of the Temp class !!!
3,247,632
3,247,731
c++ cout with float producing strange results
Currently I have the following: float some_function(){ float percentage = 100; std::cout << "percentage = " << percentage; //more code return 0; } which gives the output percentage = 100 However when I add some std::endl like so: float some_function(){ float percentage = 100; std::cout << "percentage = " << percentage << std::endl; //more code return 0; } This gives the output: percentage = 1000x6580a8 Adding more endl's just prints out more 0x6580a8's. What could be causing this? This is compiled with gcc 4.4.3 on Ubuntu 10.04.
Your code is perfectly valid. I suspect that you could be smashing your stack or heap in some other part of your code as the most likely cause. 0x6580a8 is too short to be an object address. Also, he would never get the same address in two runs of the same program.
3,247,660
3,247,822
C++ Reading signed 32-bit integer value
I have a multi-byte primitive type called s32 which I want to read from a byte array. The specifications are: It is a 32-bit signed integer value, stored in little-endian order. Negative integers are represented using 2's complement. It uses 1 to 5 bytes depending on the magnitude. Each byte contributes its low seven bits to the value. If the high (8th) bit is set, then the next byte is also a part of the value. Sign extension is applied: the seventh bit of the last byte of the encoding is propagated to fill out the 32 bits of the decoded value. In the case of U32 - unsigned 32-bit I come up with this (any comments welcomed!) but not sure how to modify it for S32. char temp = 0; u32 value = 0; size_t index = 0; for(int i = 0; i < 5; i++) { if(i < 4) { temp = 0x7F & buffer[index]; } else { temp = 0x0F & buffer[index]; } value |= temp << (7 * i); if(!(0x80 & buffer[index])) break; ++index; } Thanks everyone!
Are you working on a little-endian system? If so following should do the trick. if(!(0x80 & buffer[index])) { if(0x40 & buffer[index]) value = -value; break; } If you need the negative of a little endian value on a big endian system, then it is a bit more tricky, but that requirement would seem very strange to me
3,247,667
3,248,372
Which is the default C++0x mode in Visual C++ 2010 Express?
I have just installed Visual C++ 2010 Express and I have the impression that the default mode includes C++0x features and the std::tr1 library. error C2872: 'is_same' : ambiguous symbol could be 'C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\type_traits(941) : std::tr1::is_same' Could you confirm that? If this is the case, is there some way to disable the default settings? Why the tr1 symbols are visible? is there a using inside the MS headers?
YES : VC10 provide some C++0x featrues (auto, decltype, r-value reference, etc) and std::tr1 inside std namespace and it's not optional AFAIK. However, you can still use VS2010 with VC9 (that don't have those features) if you have it installed too. To do this, just change the compiler version in the project setting from 100 (vc10) to 90 (vc9). In this context, std::tr1 will be available in std::tr1 namespace.
3,247,671
3,247,689
Accessing protected members in a derived class
I ran into an error yesterday and, while it's easy to get around, I wanted to make sure that I'm understanding C++ right. I have a base class with a protected member: class Base { protected: int b; public: void DoSomething(const Base& that) { b+=that.b; } }; This compiles and works just fine. Now I extend Base but still want to use b: class Derived : public Base { protected: int d; public: void DoSomething(const Base& that) { b+=that.b; d=0; } }; Note that in this case DoSomething is still taking a reference to a Base, not Derived. I would expect that I can still have access to that.b inside of Derived, but I get a cannot access protected member error (MSVC 8.0 - haven't tried gcc yet). Obviously, adding a public getter on b solved the problem, but I was wondering why I couldn't have access directly to b. I though that when you use public inheritance the protected variables are still visible to the derived class.
A class can only access protected members of instances of this class or a derived class. It cannot access protected members of instances of a parent class or cousin class. In your case, the Derived class can only access the b protected member of Derived instances, not that of Base instances. Changing the constructor to take a Derived instance will solve the problem.
3,247,717
3,248,382
Image sequence transfer using socket, noob question
I am building an C++ application server-client where the client sends an image (170kb) to a server every 200ms. Using UDP, the files uncompressed are over 64kbs allowed by each datagram (I'd like to avoid compressing the files if possible). On the other hand I'm having problems setting a TCP connection, I managed stablish a connection but only the first file is sent, do I need to connect, send the file, break connection and do the same process for all files? Both sockets were set up using boost asio. Should I another protocol? thanks in advance
First of all, don't use UDP for that. TCP was designed for what you need and does a lot already by itself. From you POV, TCP connections will always somehow work, whereas with UDP, you'll have to take care of packet sequencing, packets missings, etc. For example, an image takes 3 packets to transfer, UDP does not guarantee that all 3 packes will arive at the destination, and if they do, it does not guarantee that they'll arrive in the same order you've sent. Now, for TCP, reestablishing a new connection for every file could be done, yes, but it is not necessary. Ideally your code should check to see if the connection is established, if not, reconnect. Now, why is only the 1st file transferred, I cannot guess why, since it is most likely due to your implementation (i.e. I can't see the code through my crystal ball, it must be uncharged or something ;-) ). But the point is, it is certainly not because of any limmitations of TCP or Boost::ASIO.
3,247,837
3,248,418
Strange debugger problem?
I have created this datastructure: class Event { public: Event(EVENT_TYPE type, void* pSender = 0, int content1 = 0, int content2 = 0, int content3 = 0, int content4 = 0); ~Event(void); // ... some functions protected: EVENT_TYPE itsType; void* itsPointerToSender; int itsContent_1; int itsContent_2; int itsContent_3; int itsContent_4; int numStacked; }; whose constructor is simply Event::Event(EVENT_TYPE type, void* pSender, int content1, int content2, int content3, int content4) : itsType(type), itsPointerToSender(pSender), itsContent_1(content1), itsContent_2(content2), itsContent_3(content3), itsContent_4(content4), numStacked(0) { } For some strange reason I can't understand, the VS debugger cannot and will not show me whatever is contained in itsContent_4. If I put a watch on the variable, itsContent_4 gives me a symbol "itsContent_4" not found while doing the same thing with itsContent_3 works perfectly. I'm not sure the variable even exists as far as the compiler is concerned! Am I missing something here? Edit: Now it seems (even stranger) that changing the order of the variables in the declaration creates an even bigger mess! I tried placing itsContent_4 before itsContent_1 and now itsContent_1 is being initialized with the value intended for itsContent_4! What is going on here? I'm suspecting something to do with naming, so I'll try renaming them all and see what happens. Edit 2: Yes, apparently changing the variable names to itsContent_a instead of itsContent_1 and so forth works perfectly. Is there some restriction as to using numbers in a variable name?
Sounds to me like the debugger is using the wrong .pdb file. Tools + Options, Debugging, General, ensure that "Require source files to exactly match the original version" is checked. While debugging with a breakpoint active, use Debug + Windows + Modules and right-click your executable in the list. Click "Symbol Load Information" to find out where the debugger found the .pdb file. Another possible mishap is that this class is defined in a separately compiled executable, like a DLL, which was compiled with incompatible settings. So that the layout of the object no longer matches. That's not that likely in this case.
3,247,861
3,248,017
Example of UUID generation using Boost in C++
I want to generate just random UUID's, as it is just important for instances in my program to have unique identifiers. I looked into Boost UUID, but I can't manage to generate the UUID because I don't understand which class and method to use. I would appreciate if someone could give me any example of how to achieve this.
A basic example: #include <boost/uuid/uuid.hpp> // uuid class #include <boost/uuid/uuid_generators.hpp> // generators #include <boost/uuid/uuid_io.hpp> // streaming operators etc. int main() { boost::uuids::uuid uuid = boost::uuids::random_generator()(); std::cout << uuid << std::endl; } Example output: 7feb24af-fc38-44de-bc38-04defc3804de
3,248,135
3,248,159
Book about programming in Windows 7
Could anyone recommend good book about programming in windows 7 in C++?
It is not a book in the classical sense, but it is great, extremely comprehensive when it comes to the Windows API (all new Windows 7 technologies are covered), and normative: MSDN.
3,248,255
3,248,354
Why doesn't C++ have virtual variables?
This might have been asked a million times before or might be incredibly stupid but why is it not implemented? class A { public: A(){ a = 5;} int a; }; class B:public A { public: B(){ a = 0.5;} float a; }; int main() { A * a = new B(); cout<<a->a; getch(); return 0; } This code will access A::a. How do I access B::a?
To access B::a: cout << static_cast<B*>(a)->a; To explicitly access both A::a and B::a: cout << static_cast<B*>(a)->A::a; cout << static_cast<B*>(a)->B::a; (dynamic_cast is sometimes better than static_cast, but it can't be used here because A and B are not polymorphic.) As to why C++ doesn't have virtual variables: Virtual functions permit polymorphism; in other words, they let a classes of two different types be treated the same by calling code, with any differences in the internal behavior of those two classes being encapsulated within the virtual functions. Virtual member variables wouldn't really make sense; there's no behavior to encapsulate with simply accessing a variable. Also keep in mind that C++ is statically typed. Virtual functions let you change behavior at runtime; your example code is trying to change not only behavior but data types at runtime (A::a is int, B::a is float), and C++ doesn't work that way. If you need to accommodate different data types at runtime, you need to encapsulate those differences within virtual functions that hide the differences in data types. For example (demo code only; for real code, you'd overload operator<< instead): class A { public: A(){ a = 5;} int a; virtual void output_to(ostream& o) const { o << a; } }; class B:public A { public: B(){ a = 0.5;} float a; void output_to(ostream& o) const { o << a; } }; Also keep in mind that making member variables public like this can break encapsulation and is generally frowned upon.
3,248,456
3,248,539
Decimal to Binary, strange output
I wrote program to convert decimal to binary for practice purposes but i get some strange output. When doing modulo with decimal number, i get correct value but what goes in array is forward slash? I am using char array for being able to just use output with cout <<. // web binary converter: http://mistupid.com/computers/binaryconv.htm #include <iostream> #include <math.h> #include <malloc.h> // _msize #include <climits> #define WRITEL(x) cout << x << endl; #define WRITE(x) cout << x; using std::cout; using std::endl; using std::cin; char * decimalToBinary(int decimal); void decimal_to_binary_char_array(); static char * array_main; char * decimalToBinary(int decimal) // tied to array_main { WRITEL("Number to convert: " << decimal << "\n"); char * binary_array; int t = decimal, // for number of digits digits = 0, // number of digits bit_count = 0; // total digit number of binary number static unsigned int array_size = 0; if(decimal < 0) { t = decimal; t = -t; } // if number is negative, make it positive while(t > 0) { t /= 10; digits++; } // determine number of digits array_size = (digits * sizeof(int) * 3); // number of bytes to allocate to array_main WRITEL("array_size in bytes: " << array_size); array_main = new char[array_size]; int i = 0; // counter for number of binary digits while(decimal > 0) { array_main[i] = (char) decimal % 2 + '0'; WRITE("decimal % 2 = " << char (decimal % 2 + '0') << " "); WRITE(array_main[i] << " "); decimal = decimal / 2; WRITEL(decimal); i++; } bit_count = i; array_size = bit_count * sizeof(int) + 1; binary_array = new char[bit_count * sizeof(int)]; for(int i=0; i<bit_count+1; i++) binary_array[i] = array_main[bit_count-1-i]; //array_main[bit_count * sizeof(int)] = '\0'; //WRITEL("\nwhole binary_array: "); for(int i=0; i<array_size; i++) WRITE(binary_array[i]); WRITEL("\n"); delete [] array_main; return binary_array; } int main(void) { int num1 = 3001; // 3001 = 101110111001 // 300 = 100101100 // 1000 = 1111101000 // 1200 = 10010110000 // 1000000 = 11110100001001000000 // 200000 = 110000110101000000 array_main = decimalToBinary(num1); WRITEL("\nMAIN: " << array_main); cin.get(); delete [] array_main; return 0; } The output: Number to convert: 3001 array_size in bytes: 48 decimal % 2 = 1 / 1500 decimal % 2 = 0 0 750 decimal % 2 = 0 0 375 decimal % 2 = 1 1 187 decimal % 2 = 1 / 93 decimal % 2 = 1 1 46 decimal % 2 = 0 0 23 decimal % 2 = 1 1 11 decimal % 2 = 1 1 5 decimal % 2 = 1 1 2 decimal % 2 = 0 1 1 decimal % 2 = 1 1 0 MAIN: 1111101/100/ What are those forward slashes in output (1111101/100/)?
It must be array_main[i] = (char) (decimal % 2 + '0'); (note the parentheses). But anyway, the code is horrible, please write it again from scratch.
3,248,469
3,248,483
Returning *this with an assignment operator
I went over making my own copy constructor and it overall makes sense to me. However, on the topic of doing your own assignment operator I need someone to fill in the blank for me. I pretty much don't get why you are returning *this in all the examples, such as the one below: Foo & Foo::operator=(const Foo & f) { //some logic return *this; } So if I have some statements like: Foo f; f.hour = 7; Foo g; g = f; Once the assignment operator runs, it returns a reference to the g object (the *this). So now the question is, won't I now have a statement implicitly like this?: g = g (g being a reference) The thing is, before, setting a reference to just an object would have caused the copy constructor to be invoked. In this case, it doesn't even though it fits the signature of the copy constructor.
You want to return *this so you can chain =: Foo f, g, h; f = g = h; This is basically assigning h into g, then assigning g (returned by return *this) into f: f = (g = h); Another situation this is sometimes used in is having an assignment in a conditional (considered bad style by many): if ( (f = 3).isOK() ) { With the statement g = f; the return is just ignored, like if you did 3 + 4;.
3,248,554
3,250,303
What's the difference between set<pair> and map in C++?
There are two ways in which I can easily make a key,value attribution in C++ STL: maps and sets of pairs. For instance, I might have map<key_class,value_class> or set<pair<key_class,value_class> > In terms of algorithm complexity and coding style, what are the differences between these usages?
Set elements cannot be modified while they are in the set. set's iterator and const_iterator are equivalent. Therefore, with set<pair<key_class,value_class> >, you cannot modify the value_class in-place. You must remove the old value from the set and add the new value. However, if value_class is a pointer, this doesn't prevent you from modifying the object it points to. With map<key_class,value_class>, you can modify the value_class in-place, assuming you have a non-const reference to the map.
3,248,704
3,259,131
C++ vs PHP performance on PCA
May I know whether C++ or PHP is more efficient on running PCA (Principal Component Analysis)? I'm developing a web based system which get uploaded image with php, and then process the image so that I can analyse the image with PCA to find out whether the image match with another image which already stored in database. But I'm wondering which language to use (C++ or PHP or any other better alternative) for a better performance to complete the PCA task. tq~
Generally speaking, in computationally intensive projects, code doing the same steps is 100 times faster in C (or C++ for that matter) compared to PHP. Optimizing your C will give another 2-10 times increase, depending on the time, effort and knowledge you put in. The point is that PHP is interpreted, and C runs, loosely speaking, almost directly on your cpu. If you really want to get the most out of it, in C you can go down the SSE1/2/3/4 road. You could of course use or write a library (or call it "extension") for PHP in C, which in my experience is a good match to achieve high speed at the right points while keeping the benefits of PHP.
3,248,726
3,248,743
Freeing allocated memory
Is this good practice? Or should I just replace the code block between { and } with a function? It could be reusable (I admit) but my only motivation for doing this is to deallocate colsum since it's huge and not required so that I can free the allocated memory. vector<double> C; { vector<double> colsum; A.col_sum(colsum); C = At*colsum; } doSomething(C);
Using brackets to scope automatic variables is fine in my book, but generally if you find yourself doing it a lot, especially multiple times in the same function, your function is probably doing too many different things and should be broken up.
3,248,818
3,434,969
boost::iostreams::zlib::default_noheader seems to be ignored
I'm having trouble getting boost::iostreams's zlib filter to ignore gzip headers ... It seems that setting zlib_param's default_noheader to true and then calling zlib_decompressor() produces the 'data_error' error (incorrect header check). This tells me zlib is still expecting to find headers. Has anyone gotten boost::iostreams::zlib to decompress data without headers? I need to be able to read and decompress files/streams that do not have the two-byte header. Any assistance will be greatly appreciated. Here's a modified version of the sample program provided by the boost::iostreams::zlib documentation: #include <fstream> #include <iostream> #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/zlib.hpp> int main(int argc, char** argv) { using namespace std; using namespace boost::iostreams; ifstream ifs(argv[1]); ofstream ofs("out"); boost::iostreams::filtering_istreambuf in; zlib_params p( zlib::default_compression, zlib::deflated, zlib::default_window_bits, zlib::default_mem_level, zlib::default_strategy, true ); try { in.push(zlib_decompressor(p)); in.push(ifs); boost::iostreams::copy(in, ofs); ofs.close(); ifs.close(); } catch(zlib_error& e) { cout << "zlib_error num: " << e.error() << endl; } return 0; } I know my test data is not bad; I wrote a small program to call gzread() on the test file; it is successfully decompressed ... so I'm confused as to why this does not work. Thanks in advance. -Ice
I think what you want to do is something that's described here which is to adjust the window bits parameter. e.g zlib_params p; p.window_bits = 16 + MAX_WBITS; in.push(zlib_decompressor(p)); in.push(ifs); MAX_WBITS is defined in zlib.h I think.
3,248,925
3,261,014
how does OpenID differ between different logins on the same OpenID endpoint
I am trying to implement an own OpenID endpoint based on SMF user accounts. I based my code on phpMyOpenID and some SMF authorization code. It works fine so far. I can use the endpoint to login/register on any site. If I am not logged in on the SMF, it will ask for my login and if that SMF login is successful, it accepts it. However, it seems that it doesn't differ between different SMF logins. I.e. another user reported that he tried to use the endpoint on site X, logged in with his SMF account and landed on my user account on site X (I have registered the OpenID endpoint earlier on that site). I guess I must send somehow the SMF login or make it somehow unique per SMF login. As it is probably trivial what I have to do, I thought I'd ask here on SO -- maybe there are also more things I need to fix. The code (just PHP), if you want to take a look, is here: http://github.com/albertz/smf-openid-server Or maybe just describe what I need to do to make it unique for each SMF login. Another project I am planning is an OpenID client in a multiplayer C++ game. The hoster will have the option to allow only logins from people who can authenticate via OpenID. Also I want to make it possible to allow only certain people to login. What is a common way to get a unique string based on an OpenID login? In this case, I thought of something like http://{smf-openid-endpoint}/{smf-user} or http://www.google.de/profiles/{google-user}. What is a canonical way to get such a string? I think this other question may be related to my main question, that is why I am putting it also here. See also the related question: Is the identifier URL unique? What are the different terms?
It seems the first request from the end user I am getting is checkid_setup. On that response, I can specify a unique URL (what I call the unique string in my question) in the openid.identity field. I have done that in my code now and it seems to work. I.e. I can enter the general OpenID endpoint URL (for example on SourceForge) and it will extend it automatically in the way I have suggested in my question. To answer my second question: It seems that the verified identifier URL itself is unique, so this could be used. Whereby this can sometimes look cryptic (for example in case of Google, it is just some hash). So this can be used internally to differ between different users. For the graphical representation, I can show the real username or the mail address which I also should get from the OpenID authentication.
3,249,139
3,249,227
Can't Read in two strings separated by a space
I am trying to read in two strings separated by a space. cin>>a; cin>>b; This should technically work. I have also used getline but it doesnt seem to work. It reads in some of the inputs and gets stuck on others Edit: Added C++ tag, kept C tag since it's part of the original post.
This: #include <iostream> #include <sstream> int main() { std::istringstream iss("wrgl zrgl"); std::string s1, s2; iss >> s1 >> s2; std::cout << '"' << s1 << "\" \"" << s2 << "\"\n"; return 0; } compiles, runs, and prints "wrgl" "zrgl" on my machine.
3,249,147
3,249,527
Unexpected const reference behavior
#include <iostream> class A { public: A(){ cerr << "A Constructor" << endl; } ~A(){ cerr << "A Destructor" << endl; } A(const A &o){ cerr << "A Copy" << endl; } A& operator=(const A &o){ cerr << "A Assignment" << endl; return *this; } }; class B : public A { public: B() : A() { cerr << "B Constructor" << endl; } ~B(){ cerr << "B Destructor" << endl; } private: B(const B &o) : A() { cerr << "B Copy" << endl; } B& operator=(const B &o){ cerr << "B Assignment" << endl; return *this; } }; int main() { A a; const A &b = B(); return 0; } In GCC 4.2, I get this message: In function 'int main()': Line 16: error: 'B::B(const B&)' is private compilation terminated due to -Wfatal-errors. If I remove the "private" from B, I get the output I expect: A Constructor A Constructor B Constructor B Destructor A Destructor A Destructor My question is: why does making a method which isn't called private change whether this code compiles? Is this standard-mandated? Is there a workaround?
The important verbiage in the current standard (C++03) seems to be in §8.5.3, which explains how references are initialized (In these quotes, T1 is the type of the reference being initialized and T2 is the type of the initializer expression). If the initializer expression is an rvalue, with T2 a class type, and "cv1 T1" is reference-compatible with "cv2 T2," the reference is bound in one of the following ways (the choice is implementation-defined): -- The reference is bound to the object represented by the rvalue (see 3.10) or to a sub-object within that object. -- A temporary of type "cv1 T2" [sic] is created, and a constructor is called to copy the entire rvalue object into the temporary. The reference is bound to the temporary or to a sub-object within the temporary. The constructor that would be used to make the copy shall be callable whether or not the copy is actually done. So, even if the implementation binds the reference directly to the temporary object, the copy constructor must be accessible. Note that this is changed in C++0x, per the resolution of CWG defect 391. The new language reads (N3092 §8.5.3): Otherwise, if T2 is a class type and -- the initializer expression is an rvalue and "cv1 T1" is reference-compatible with "cv2 T2," -- T1 is not reference-related to T2 and the initializer expression can be implicitly converted to an rvalue of type "cv3 T3" (this conversion is selected by enumerating the applicable conversion functions (13.3.1.6) and choosing the best one through overload resolution (13.3)), then the reference is bound to the initializer expression rvalue in the first case and to the object that is the result of the conversion in the second case (or, in either case, to the appropriate base class subobject of the object). The first case applies and the reference is "bound directly" to the initializer expression.
3,249,150
3,249,229
Pointer seen by Visual Studio as a void**
something strange is happening to my code. I am using a library which is supposed to work perfectly (nglib from the open-source Netgen mesher). I can link and include everything, but I cannot use this library : The object I want to use is Ng_Mesh* mesh = Ng_NewMesh (); The Ng_NewMesh() method is : DLL_HEADER Ng_Mesh * Ng_NewMesh () { Mesh * mesh = new Mesh; mesh->AddFaceDescriptor (FaceDescriptor (1, 1, 0, 1)); return (Ng_Mesh*) (void*) mesh; } When I go to locals, it is seen as a void** referring to *mesh which is a void*. It is not NULL because I can add points and other stuff to this object, but with some functions, I get an exception : System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at nglib.Ng_GetPoint(Void** , Int32 , Double* ) at ForwardModelingPlugin.CustomMeshVol3D.tesselate(CustomMeshVol3D* ) nglib.Ng_GetPoint is supposed to have as arguments (Ng_Mesh*, Int32, Double*) which explains this exception. I don't know why this casting is happening.
Here it says: /// Data type for NETGEN mesh typedef void * Ng_Mesh; therefore Ng_Mesh* mesh; is the same as void** mesh;
3,249,358
3,249,425
c++ exception-like message passing
I'm working on developing a fairly robust 2D game engine as a base that other games can be built off of as a for-fun project (I know theres already things that do this, but that's no fun). I'm trying to figure out a good way to do message-passing between classes within the engine. At first I was thinking about using a heirarchy of exceptions and throwing them whenever something required it. But as I was developing that way, I realized that there was quite a large number of exceptions being thrown, as they were being used for fairly common things (part of subroutines that handle pathfinding and unit locating and things that need to test the state of the game board alot). The exceptions were being used for things like the pathfinding came across a unit in the way and needed to go around it, it would throw a TileOccupied exception and the pathfinding could gracefully handle that and continue. As can be expected, this created a lot of exceptions. The internet has told me that exceptions are expensive due to all the run-time processing they need to do. But they handle what I need perfectly, which is being able to propogate a message back to the caller even through branching subroutines to indicate when something has happened or something was not as expected. Is there any clean/efficient way to do this in c++? Or am I structuring things very wrongly if I am using this type of notification? I'm still learning, so any suggestions would be greatly appreciated (and I'm willing to read / learn any references you can throw my way) Edit I'm trying to do this in standard c++ btw. I am writing it on linux, and want it to compile and be runnable platform-independent. I'm currently using Boost in it.
Although this requires explicit registration, this sounds like you want callbacks (eased by e.g. Boost.Function) or signals (like Boost.Signals/Signals2).
3,249,452
3,249,547
C++: speed of std::stack::pop() method
I'm writing a lighter version of some containers from STL for myself. (I know that STL was written by professional programmers and I am too stupid or too ambitious if think that I can write it better than they did. When I wrote my list (only with method I need), it worked few times faster. So, I thought it's a good idea. But, anyway.) I was disappointed by speed of std::stack::pop(). I glanced at souses and found that there's no great algorithm. Nearly as I did, I suppose: void pop() { if(topE) // topE - top Element pointer { Element* n_t = topE->lower; // element 'under' that one delete topE; topE = n_t; } } But it works much slower than STL's one. erase(--end()); Can anybody explain me why iterator erase is faster?
Because of delete topE. With STL (at least for the SGI implementation), there is no automatic delete on pop(). If you've dynamically allocated the elements in the stack, it's up to you to deallocate before calling pop(). The STL pop just shortens the stack size by one (and destroys the last object - not necessarily a heap delete). The next thing is that (it looks like) you're using a linked list to store the stack. That's going to be wayyyy slower than the default STL container (SGI uses deque) because you'll lose cache locality and require dynamic allocation for each element (new/delete) - whereas a deque will dynamically allocate chunks of the stack at a time. You said it best: STL was written by professional programmers and I am too stupid or too ambitious if think that I can write it better than they did At least for now :) Try and see how close you get!
3,249,638
3,249,650
How can private member variables in a superclass be accessed in a subclass?
I want to do something like: /* * Superclass.h * */ class Superclass { const int size; public: Superclass():size(1){} ~Superclass(){} }; /* * Subclass.h * */ #include "Superclass.h" class Subclass : public Superclass { public: Subclass(){size;} ~Subclass(){} };
Use protected instead of private
3,249,738
4,483,294
get_driver_instance() crashes with Qt
I'm trying to User MySQL Connector/C++ with Qt, and had spent hours pulling my hairs on a problem. Here's a SIMPLE code to test out the connection: int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); cout << "aa" << endl; sql::Driver *driver; try { driver = get_driver_instance(); } catch(exception &e) { cout << e.what() << endl; } cout << "aa" << endl; return a.exec(); } It build and compiles fine, however whenever it calls get_driver_instance(), it crashes and just give me XXX.exe has stopped working. I'm using Qt Creator, windows Vista, my .pro file is as follow: QT += core QT += sql QT -= gui TARGET = friendsDB CONFIG += console CONFIG -= app_bundle LIBS += "C:\Program Files\MySQL\MySQL Connector C++ 1.0.5\lib\debug\mysqlcppconn.lib" INCLUDEPATH += "C:\Program Files\MySQL\MySQL Connector C++ 1.0.5\include" TEMPLATE = app SOURCES += main.cpp Any light shed would be greatly appreciated, thanks
From the documentation of MySQL Connector: "One problem that can occur is when the tools you use to build your application are not compatible with the tools used to build the binary versions of MySQL Connector/C++. Ideally you need to build your application with the same tools that were used to build the MySQL Connector/C++ binaries." And to repeat the question of akira: Why don't you use the QMYSQL drivers?
3,250,044
3,250,262
Switching the "Files of type" pull-down in .NET OpenFileDialog clears the list of files bug
I'm trying to use the .NET class OpenFileDialog in C++ and getting a weird bug. My basic code is below. OpenFileDialog^ openFileDialog = gcnew OpenFileDialog; openFileDialog->InitialDirectory = "c:\\"; openFileDialog->Filter = "Bitmap|*.bmp|All Files|*.*"; openFileDialog->FilterIndex = 1; openFileDialog->RestoreDirectory = true; if (openFileDialog->ShowDialog() == DialogResult::OK) MessageBox::Show(openFileDialog->FileName, "Information", MessageBoxButtons::OK, MessageBoxIcon::Information); When the code reaches this point, the dialog opens as expected. But if I switch the "Files of type" pull-down, as a user might, the files and directories that are listed in the dialog window disappear (irrespective of the filter). If I go up to the parent directory, and re-enter the same child directory, then the files and directories are properly displayed, filtered as expected. Does anyone have any idea why I might be getting this weird bug? FYI, I'm on a Windows XP 64-bit SP2, building with Visual Studio 2010 for .NET 4.
This is pure operating system behavior. The dialog lives in the shell, the .NET wrapper class is a very thin one around GetOpenFileName(). I don't know much about XP x64, except that it was training wheels for Vista x64. It wasn't done with several COM servers not yet translated to x64. And that it didn't get the SP3 update sounded iffy to me. You can assume that your customer is unlikely to see the same problem. I'm not close to one right now to verify that.
3,250,056
3,250,144
C/C++ within Ruby code?
C/C++ would be good option to write some of the performance critical aspects of a Ruby Application. I know this is possible. I would like to know how to add C/C++ code into Ruby code; any other language for that matter. Are there any practical applications of this which you noticed in open source projects or else?
Besides "Extending Ruby", here are two other resources: README.EXT (extension.rdoc) - shows you more about how to build C extensions. A good compliment to "Extending Ruby" Ruby Inline - This is a library that tries to make it easier to build C extensions by having you call methods in ruby to compile C code.
3,250,123
3,250,450
What would a std::map extended initializer list look like?
If it even exists, what would a std::map extended initializer list look like? I've tried some combinations of... well, everything I could think of with GCC 4.4, but found nothing that compiled.
It exists and works well: std::map <int, std::string> x { std::make_pair (42, "foo"), std::make_pair (3, "bar") }; Remember that value type of a map is pair <const key_type, mapped_type>, so you basically need a list of pairs with of the same or convertible types. With unified initialization with std::pair, the code becomes even simpler std::map <int, std::string> x { { 42, "foo" }, { 3, "bar" } };
3,250,181
3,250,222
Overhead of retrieval of an object compared to storing in local
Suppose you have a private static method called Inst() which allows the class to retrieve the single instance of itself in the application in its static methods. Maybe Inst() is defined something like.. return App::GetApp()->CurrentState()->MyClass(); // Inst returns a reference Compare this... // I prefer this Inst().DoThis(); Inst().DoThat(); Inst().DoFoo(); to... MyClass inst = Inst(); inst.DoThis(); inst.DoThat(); inst.DoFoo(); In an application where performance is fairly important, is the overhead in the first set of functions non-trivial? Are modern compilers able to optimize these things out? I realize profiling would answer my question in my case, but I'm looking for a rule of thumb here. How beneficial is it to store existing data in an local variable rather than re-retrieving it, or is this re-retrieval commonly optimized by modern compilers?
You worry about the wrong things and have answered the question yourself. Profile it and optimize if it's a bottleneck. Anyway: Inst() is probably going to be inlined, so there is no function call overhead and as it is static and the result is not depending on any obvious outside parameters it could be possible for compilers to optimize it away entirely.
3,250,195
3,250,285
else if string compare problem
I have the following if statements, two of which don't seem to work. I don't get why it works when I try to compare it to a single character "y" or "n" but not when I try to compare it to two characters in one else if statement. The last question I have is if there's a better cleaner way to write this or if this acceptable for a simple prompt check? getline(cin,somestr); if(somestr.empty()){ //do this } else if (somestr == "y" || "Y"){ //do something else } else if (somestr == "n" || "N"){ //do something else } else{}
Unfortunately, the language doesn't give you an easy way to check a variable against a set of possibilities. You have to do each test individually or use a switch statement. So, either of the following code samples would be a valid solution for your problem: else if (somestr == 'y' || somestr == 'Y'){ //do something else } else if (somestr == 'n' || somestr == 'N'){ //do something else } switch (somestr) { case 'y': case 'Y': // do something break; case 'n': case 'N': // do something break; default: break; } Alternatively, you can clean up your code a bit by reducing some of your logic (assuming somestr is a char): // Convert to uppercase first and only one comparison is needed else if (toupper(somestr) == 'Y'){ //do something else } else if (toupper(somestr) == 'N'){ //do something else }
3,250,217
3,250,246
C++ inheritance question
I have the following problem in application architecture and am willing to solve it (sorry for a lot of text). I am building a game engine prototype and I have base abstract class AbstractRenderer (I will use C++ syntax, but still the problem is general). Assume there are some derived implementations of this renderer, let's say DirectxRenderer and OpenglRenderer. Now, let's say that only one of these renderers (let's stick to DirectX-based) has a member called IDirect3D9Device* m_device; Obviously at this point everything is fine - m_device is used internally in DirectxRenderer and shouldn't be exposed in the abstract AbstractRenderer superclass. I also add some abstract rendering interface, for instance IRenderable. It means simply one pure virtual method virtual void Render(AbstractRenderer* renderer) const = 0; And this is the place where some problems start. Assume I am modelling some scene, so, this scene will probably have some geometrical objects in it. I create abstract superclass AbstractGeometricalObject and derived DirectX-based implementation DirectxGeometricalObject. The second one would be responsible for storing pointers to DirectX-specific vertex & index buffers. Now - the problem. AbstractGeometricalObject should obviously derive the IRenderable interface, because it's renderable in logical terms. If I derive my DirectxGeometricalObject from AbstractGeometricalObject, the first one should have virtual void Render(AbstractRenderer* renderer) const { ... } method in it, and that Abstract... stuff brings some troubles. See the code for better explanation: And for now my classes look the following way: class AbstractGeometricalObject : public IRenderable { virtual void Render(AbstractRenderer* renderer) const { ... } }; class DirectxGeometricalObject : public AbstractGeometricalObject { virtual void Render(AbstractRenderer* renderer) const { // I think it's ok to assume that in 99 / 100 cases the renderer // would be a valid DirectxRenderer object // Assume that rendering a DirectxGeometricalObject requires // the renderer to be a DirectxRenderer, but not an AbstractRenderer // (it could utilize some DX-specific settings, class members, etc // This means that I would have to ***downcast*** here and this seems really // bad to me, because it means that this architecture sucks renderer = dynamic_cast<DirectxRenderer*>(renderer); // Use the DirectX capabilities, that's can't be taken out // to the AbstractRenderer superclass renderer.DirectxSpecificFoo(...); } I know I'm probably worrying too much, but this downcast in such a simple case means that I could be forced to make lots of downcasts if my application grows. Definitely, I would like to avoid this, so please, could you advice me something better in design terms / point out my errors. Thank you
This might be a situation where the template pattern (not to be confused with C++ templates) comes in handy. The public Render in the abstract class should be non-virtual, but have it call a private virtual function (e.g. DoRender). Then in the derived classes, you override DoRender instead. Here's an article that goes into great depth describing the use of template pattern with private virtual functions. Edit: I started to put together an example of what I meant, and it seems like there's actually a broader flaw in the architecture. Your use of AbstractRenderer is somewhat frivolous since you're forcing each geometricalobject to be intimately aware of a particular renderer type. Either the renderer should be able to work off the public methods of Renderables, or Renderables should be able to work off the public methods of the Renderer. Or perhaps you can give the concrete renderers a Renderable factory if there really needs to be such an intimate connection. I'm sure there are some other patterns that would fit well, too.
3,250,339
3,250,812
C++ header file variable scope issue
I've got 3 files that relate to this problem. file.h, file.C and user.C. file.h has a private member, fstream logs. In file.C's constructor it opens logs. It doesn't do this in the constructor, but the constructor calls a function OpenLog(). file.h also has an inline close function: CloseLog() {if (logs) logs.close();} The file user.C has an exit function which creates an instance of file, then calls CloseLog. It seg faults at this point. I created some other dummy tests, and it appears as though logs is lost in the mix somewhere ... Going from file.C to user.C and then back to file.C causes this. If I have fstream logs as a global in file.C then it works - but I'd rather avoid a global. Any thoughts on what I should do here? Please let me know if I should post more code about this, I can set up some dummy stuff to demo this better. ** Here's more code, as requested - I can't copy and paste, so forgive the lack of it please ** I will call the classes helpME.h, helpME.C and user.C //helpME.h #ifndef _helpME_H #define _helpME_H #include < iostream> #include < fstream> //various includes class helpME { private: fstream logs; public: void CloseLog() {if (logs) logs.close();} }; #endif //end helpME.h //helpME.C void helpME::helpME(int argc, char** argv) { //various code OpenLog(); } void helpME::OpenLog() { //logname is set above, i had a print statement before that showed this is correct logs.open(logname, ios::in | ios::out | ios::trunc); } //end helpME.C //user.C void user::quitHelpME(item) { helpME* hME = (helpME*) item; hME->CloseLog(); } //end user.C Again - please forgive the lack of clarity, I'm thinking I may have just confused things more by adding this ... this code is on another box and can't be copied over.
void user::quitHelpME(item) { helpME* hME = (helpME*) item; This doesn't create an instance, it's using C style casting to cast from whatever item is to a pointer to helpME. if item is NULL then calling a method on it will seq fault. otherwise still not enough detail in your example to give you an answer, the code present seems sound.
3,250,467
3,253,827
What is inside .lib file of Static library, Statically linked dynamic library and dynamically linked dynamic library?
What is inside of a .lib file of Static library, Statically linked dynamic library and dynamically linked dynamic library? How come there is no need for a .lib file in dynamically linked dynamic library and also that in static linking, the .lib file is nothing but a .obj file with all the methods. Is that correct?
For a static library, the .lib file contains all the code and data for the library. The linker then identifies the bits it needs and puts them in the final executable. For a dynamic library, the .lib file contains a list of the exported functions and data elements from the library, and information about which DLL they came from. When the linker builds the final executable then if any of the functions or data elements from the library are used then the linker adds a reference to the DLL (causing it to be automatically loaded by Windows), and adds entries to the executable's import table so that a call to the function is redirected into that DLL. You don't need a .lib file to use a dynamic library, but without one you cannot treat functions from the DLL as normal functions in your code. Instead you must manually call LoadLibrary to load the DLL (and FreeLibrary when you're done), and GetProcAddress to obtain the address of the function or data item in the DLL. You must then cast the returned address to an appropriate pointer-to-function in order to use it.
3,250,579
3,250,647
How do I insert data into a pre-allocated CSV?
Text file (or CSV) is: Data:,,,,,\n (but with 100 ","s) In C or C++ I would like to open the file and then fill in values between the ",". i.e.- Data:,1,2,3,4,\n I'm guessing that I need some sort of search to find the next comma, insert data, find the next comma insert, etc. I was looking at memchr() for a buffer and was wondering if there is something similar for a text file? If you could point me in the right direction, I would appreciate it. (I don't mind reading a book to find something out like this either, I just don't know what book would have this information?) Thank You.
You can't actually do that in C... if you open in read/write mode you'll overwrite characters, not insert them. http://c-faq.com/stdio/fupdate.html You need to open the file, read the line into memory, write the new line to a temp file. After you're done inserting all the lines, copy the temp file over the original file. I don't think there's any other way to do it.
3,250,841
3,251,098
ensure that an iterator dereferences to a certain type
I have to implement a function that takes an iterator. The iterator must dereference to a certain type, say int: template<typename iter> void f(iter i) { // do something here ... int t = *i; // do something here ... } The problem with this code is that if a user calls the function like this vector<string> v; v.push_back("aaa"); f(v.begin()); he will see an error pointing to some place in my code, not in his code (which will be confusing to him). I want the error to be in user's code to ease debugging.
GMan already pointed to a method to solve this via compile time assertions. There is another way to do this, which I prefer (it's my favorite C++ technique). You can put constraints on function arguments in a way that the function is ignored for overload resolution if the constraints don't fit. This is quite terrific, because you can fine tune your function overloads to arbitrary conditions. Here's how: #include <boost/utility.hpp> #include <boost/type_traits.hpp> #include <vector> template<typename Iter> typename boost::enable_if< boost::is_same<typename Iter::value_type,int>, void>::type foo(Iter it) { } int main() { std::vector<int> v; // this is OK foo(v.begin()); std::vector<double> v2; // this is an error foo(v2.begin()); } If you compile this, you will get b.cc: In function 'int main()': b.cc:19:16: error: no matching function for call to 'foo(std::vector<double>::iterator)' This is because the compiler would consider foo() only, if it's argument has a value_type type inside, which is 'int' (This is what the enable_if part means). The second call of foo() can't satisfy this constraint. enable_if is mentioned a couple of times in SO, just search for it: https://stackoverflow.com/search?q=enable_if
3,250,988
3,251,227
How well does the Visual C++ 2008/2010 compiler optimize?
Im just wondering how good the MSVC++ Compiler can optimize code(with Code examples) or what he can't optimize and why. For example i used the SSE-intrinsics with something like this(var is an __m128 value)(it was for an frustrum-culling test): if( var.m128_f32[0] > 0.0f && var.m128_f32[1] > 0.0f && var.m128_f32[2] > 0.0f && var.m128_f32[3] > 0.0f ) { ... } As i took a look at the asm-output i saw that it did compile to an ugly very jumpy version (and i know that the CPU's just hate tight jumps) and i know also that i can optimize it with the SSE4.1 PTEST instruction, but why did the compiler not do it(even if the compiler writers defined the PTEST intrinsic, so they knew the instruction)? What optimizations can't it do too (until now). Does this imply that im with the todays technology forced to use intrinsics and inline ASM and linked ASM functions and will compilers ever find such things(i don't think so)? Where can i read more about how good the MSVC++ compiler optimizes? (Edit 1): I used the SSE2 switch and FP:fast switch
The default for the compiler is set to generate code that wil run on a 'lowest common denominator' CPU - ie one without SSE 4.1 instructions. You can change that by targetting later CPUs only in the build options. That said, the MS compiler is traditionally 'not the best' when it comes to SSE optimisation. I'm not even sure if it supports SSE 4 at all. That link gives good credit to GCC for SSE optimisation: As a side note about GCC’s near perfection in code generation – I was quite surprised seeing it surpass even Intel’s own compiler Perhaps you need to change compiler!
3,251,079
3,251,116
Array stores name retrieved from GetVolumeInformation weirdly in Visual C++?
I would like to use the GetVolumeInformation call to retrieve the name of a removable device. I can retrieve the name just fine and store into a TCHAR array variable szVolNameBuff. Here is my code for that: // Get Volume Information to check for NTFS or FAT TCHAR szFileSys[256]; TCHAR szVolNameBuff[256]; DWORD dwSerial = 0; DWORD dwMFL = 0; DWORD dwSysFlags = 0; bool bSuccess; char fileType[255]; int bSuccessdebug = 0; //LPCTSTR temp = _T("E:\\"); For debugging only bSuccess = GetVolumeInformation(drivePath, szVolNameBuff, sizeof(szVolNameBuff), &dwSerial, &dwMFL, &dwSysFlags, szFileSys, sizeof(szFileSys)); When i try to print the contents of the variable with the line: printf("szVolNameBuff holds: %s \n", &szVolNameBuff); I get an output of "T" instead of the name "Transcend" which is the name of the drive. I debugged it with Visual Studio 2008 and found out that the TCHAR array stores the name as: [0] 'T' [1] 0 [2] 'R' [3] 0 [4] 'A' [5] 0 [6] 'N' [7] 0 and so on and so forth. Why is that? I want the array to store the word as just: [0] 'T' [1] 'R' [2] 'A' [3] 'N' [4] 'S' to later use it for string concatenation. Is there a way to fix this?
It looks like you are using the unicode Win32 APIs. You should use _tprintf so that the appropriate function (printf or wprintf) is used according to the character type. If you don't know unicode - here's a quick overview. The reason this is happening is that the unicode for the regular ascii characters is a null byte followed by the ascii character. That's why you are seeing the string padded with nulls. Note that when using TCHAR, you should also wrap all strings in the _T() macro, so that they are also declared of the correct type. If you follow this consistently, converting from unicode to ansi is just a matter of changing a preprocessor directive.
3,251,167
3,251,181
How to write a pointer to std::cerr?
Given: MY_CLASS* ptr = MY_CLASS::GetSomeInstance(); What is the correct way to output ptr to std::cerr, so I can log its value? Note I don't want to write the class, just the address.
operator<< is overloaded to take a const void*, so you can simply insert the pointer into the stream: std::cerr << ptr; The exception is that if the pointer is a const char*, it will be interpreted as a pointer to a C string. To print the pointer, you need to cast it explicitly to a const void*: std::cerr << static_cast<const void*>(ptr);