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,308,028
3,308,041
Default constructor value for bool type
Which value does the default constructor of the bool type return in C++? For instance, writing int i = int(); guarantees that the variable i will be initiated always with 0. I guess such an initialization routine is possible as well: bool b = bool(); But unfortunately I could not find anywhere which value such a defa...
false. Seen in the C++14 draft N4296, section 8.5 (Initializers), paragraph 6, list item 1 and references therein, and paragraph 8, list item 4.
3,308,124
3,308,646
is there a good c/c++ to delphi converter(software)
i need a tool that can convert c/c++ code to delphi(object pascal) code, have tried openc2pas but it is pretty much useless and a pain to use is their a usable alternative?(free or commercial)
Unless you need this for academic purposes, stop looking, because: Delphi doesn't support everything that's supported in C++. Examples: Delphi doesn't support operator overloading. Delphi can't instantiate class instances on stack (all Delphi objects are dynamically allocated, using the equivalent of the C++ "new" ope...
3,308,196
3,308,271
Can two windows apps communicate using the command-line?
I worked on a Unix app where two applicants ran and talked to each other using the command-line, i.e each had a loop something like (treat this as pseudo code): bool stop=false; do { stringstring cmdBuffer; cin >> cmdBuffer string ret = processCommand(cmdBuffer); if(ret.length()==0) stop=true; else co...
I'd say redirect the input and output handles(SetStdHandle), but using a named pipe is safer and more secure, plus you can use sync functions on it. you can also use a global mutex/event or Mapped memory instead, as both are globally named and easy to get/set and read/write to.
3,308,208
3,308,342
templates and function objects - c++
i have a problem with this class. the goal is to make the main function work properly. we were supposed to implement the "And" function object so that the code will work. i can't find what is the problem with our solution. (the solution start and end are marked in comments in the code before the "main" function) can yo...
The template parameter T can't be inferred, it must be specified explicitly: template <typename T, typename Function1, typename Function2> AndFunction <Function1, Function2, T> And(Function1 f1, Function2 f2) { return AndFunction<Function1, Function2, T>(f1, f2); } //***** This is where my sulotion ends ****** in...
3,308,245
3,308,513
fopen file from windows network location
I can open files from a mounted network drive, but not from an unmounted one e.g \\mycomp\folder2\hi.bmp Any work around for this?
The following snippet works for me: char buffer[1000]; FILE* file; size_t bytesRead; file = fopen("\\\\server\\share\\test.dat", "rb"); if (file != NULL) { bytesRead = fread(buffer, sizeof(char), sizeof(buffer), file); fclose(file); } Also note this excerpt from the fopen docs (MSDN): ... fopen will a...
3,308,343
3,308,669
(Ab)using constructors and destructors for side effects bad practice? Alternatives?
In OpenGL, one often writes code like this: glPushMatrix(); // modify the current matrix and use it glPopMatrix(); Essentially, the state is changed, then some actions are performed that use the new state, and finally the state is restored. Now there are two problems here: It's easy to forget to restore the state. If...
I like the idea of using RAII to control OpenGL state, but I'd actually take it one step further: have your WithFoo class constructor take a function pointer as a parameter, which contains the code you want to execute in that context. Then don't create named variables, and just work with temporaries, passing in the act...
3,308,523
3,308,690
How to eliminate external lib/third party warnings in GCC
In the software project I'm working on, we use certain 3rd party libraries which, sadly, produce annoying gcc warnings. We are striving to clean all code of warnings, and want to enable the treat-warnings-as-errors (-Werror) flag in GCC. Is there a way to make these 3rd party generated warnings, which we cannot fix, to...
I presume you are talking about the warnings coming from the 3rd party library headers. The GCC specific solution would be to create another wrapper header file which has essentially the two lines: #pragma GCC system_header #include "real_3rd_party_header.h" And use the wrapper instead of the original 3rd party header...
3,308,603
3,308,660
preventing window maximisation/minimisation in x window system
i'm writing some low level window code for a window in x (in c++), and I want to prevent the user from either maximising or minimising the window. i don't mind whether this is done by rejecting the request to resize, or by removing the buttons themselves. however, i am tied to x and can't use qt or other higher-level l...
you can't. essentially you would fight like hell against the window manager (and against the user in the end). eg, you could watch PropertyNotify events to check if your window (or rather the window your window is attached to (provided by the window manager)) gets minimized. and then you unminimize it. and then the use...
3,309,042
3,309,123
Is this self initialization valid?
I have this question, which i thought about earlier, but figured it's not trivial to answer int x = x + 1; int main() { return x; } My question is whether the behavior of the program is defined or undefined if it's valid at all. If it's defined, is the value of x known in main?
I'm pretty sure it's defined, and x should have the value 1. §3.6.2/1 says: "Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place." After that, I think it's all pretty straightforward.
3,309,089
3,309,115
Why do some experienced programmers write comparisons with the value before the variable?
Possible Duplicates: How to check for equals? (0 == i) or (i == 0) Why does one often see “null != variable” instead of “variable != null” in C#? I've been having a look at an odd tutorial here and there as well as some DirectX code and noticed that many experienced C++ programmers write expressions in the following...
Yes, that's correct. It's to detect the typo of = instead of ==.
3,309,090
3,309,178
How to sort std::list<..>
i have a list of Elemtents of a custom type: std::list<CDataTransferElement*> m_list; The class is defined like this: class CDataTransferElement { public: CDataTransferElement(void); ~CDataTransferElement(void); CString Name; double PercentValue; double MOLValue; int PhaseIndex; }; I hav...
Loop through your list adding each CDataTransferElement to a new list stored in a map. std::map<int,std::list<CDataTransferElement*> > m; for( std::list<CDataTransferElement*>::iterator i=m_list.begin(); i!=m_list.end(); ++i) { m[ (*it)->PhaseIndex ].append( (*it) ); } You can then loop over the map to do whatever y...
3,309,170
3,309,225
How to make a less than comparison in template meta-programming?
I had this question asked of me on Monday and for the life of me I don't know how to answer. Since I don't know, I now want to very much find out. Curiosity is killing this cat. Given two integers, return the lesser at compile time. template<int M, int N> struct SmallerOfMandN{ //and magic happenes here }; Got ...
That is called the minimum of two numbers, and you don't need world heavy weight library like mpl to do such a thing: template <int M, int N> struct compile_time_min { static const int smaller = M < N ? M : N; }; int main() { const int smaller = compile_time_min<10, 5>::smaller; } Of course if it was C++0x y...
3,309,379
3,320,476
C++ Copy through assignment problem
I seem to be having trouble with the following function: void OtherClass::copy_this( int index, MyClass &class_obj) { if(index < MAX_index) class_obj = array_of_MyClass[index]; } OtherClass maintains an array of MyClass objects, and I would like this function to copy a selected object out of the array into...
Should've payed attention to a few more frames back, and I would have seen the answer. The MyClass object I was trying to copy the data into had been initialized as a NULL pointer, which is where the error in memcpy() was coming from. ("Cannot access memory at address 0x0" -- d'oh!) Can't believe I missed that... Thank...
3,309,533
3,309,555
Is it possible to inline a lambda expression?
I want to inline a lambda expression since it is very short for performance reason. Is it possible?
The inline keyword does not actually cause functions to be inlined. Any recent compiler is going to make better decisions with regards to inlining than you will. In the case of a short lambda, the function will probably be inlined. If you're trying to use the inline keyword with a lambda, the answer is no, you can't us...
3,309,615
3,309,879
How do I use the latest OpenGL?
quite new to the subject, and in college we were provided with the .dlls each time we needed them. But I never had any idea what actual version I was using, what extensions I was using...This is very confusing to be honest. I couldn't find any download link on the official khronos site. Clicking on the OpenGL SDK link,...
OpenGL is not a library with different version numbers, and such. Instead it is one big standard which graphics drivers must support by themselves. Consequently, some graphics cards may not support latest OpenGL versions, while in the future some cards may not support older versions. You don't need to include a differe...
3,309,708
3,310,728
draw in a QFrame on clicking a button.
Say there is a QPushButton named "Draw", a QLineEdit and a QFrame. On clicking the button I want to take a number from QLineEdit and draw a circle in a QFrame. How can I do this? Please provide me with the code. P.S. The problem is that draw methods of the QPainter should be called in drawEvent method.
If @Kaleb Pederson's answer is not enough for you then here's a complete solution for a simple set-up matching what you describe. Tested with Qt 4.5.2 on Linux. I had some spare time... ;) main.cpp: #include <QApplication> #include "window.h" int main( int argc, char** argv ) { QApplication qapp( argc, argv ); ...
3,309,859
3,309,903
Is the reason fot the error object slicing?
g++ -std=gnu++0x main.cpp In file included from main.cpp:6:0: CustArray.h: In constructor 'CustArray::CustArray()': CustArray.h:26:32: error: 'class Info' has no member named 'someInfo' make: *** [all] Error 1 /* * Info.h * */ #ifndef INFO_H_ #define INFO_H_ class Info { friend class CustArray; }; #endif /* ...
An std::vector< std::unique_ptr<Base> > is just that: a vector filled with pointers to bases. And you cannot access derived class' content through base class pointers/references - even if objects of derived classes are behind those pointers/references. This is no different from this: SubInfo si(1); Info& info = si; ...
3,309,983
3,309,996
Does growing files on Linux cost anything?
Is there any noticeable difference in speed between these 2 scenarios? Scenario 1: I have a file of size 1024 bytes filled with 0s for every byte. I open the file and write 1024 bytes of 1s with fwrite. Scenario 2: I have a file of size 512 bytes filled with 0s for every byte. I open the file and write 1024 bytes of 1s...
This is naturally file system specific. but you can be pretty sure that growing a file can be more expensive than writing in a pre-allocated file because growing it involves file system inode allocations while writing to pre-allocated inodes does not. How big this difference actually is depends on the file system, and ...
3,310,025
3,310,221
resolve function doesn't work in boost/asio
I am learning boost/asio and writing example program which was in e-book. of course it didn't work ;) #include <boost/asio.hpp> #include <iostream> int main () { boost::asio::io_service io_service; boost::asio::ip::tcp::resolver::query query("www.boost.org", "http"); boost::asio::ip::tcp::resolver::iterator d...
you need a resolver object. Also your iterator comparison was incorrect, you need to compare against the sentinel value ip::tcp::resolver::iterator(). #include <boost/asio.hpp> #include <iostream> int main () { boost::asio::io_service io_service; boost::asio::ip::tcp::resolver::query query("www.boost.org", "htt...
3,310,065
3,310,863
Cannot order weak_ptr's in in VS10
I can not get 'operator <' to compile for a weak_ptr using VS10. Am I missing an #include or #using? Even the the code sample in the documentation does not work for me. http://msdn.microsoft.com/en-us/library/bb982759.aspx // temp.cpp : Defines the entry point for the console application. // #include "stdafx.h" // st...
It turns out that there is no uncommented 'bool operator<(const weak_ptr&, const weak_ptr&) in the header file. So contratry to the documentation, this is unsupported.
3,310,149
3,310,200
return statement in lambda expression
I created a lambda expression inside my std::for_each call. In it there is code like this one, but I have building error telling me that error: expected primary-expression before ‘return’ error: expected `]' before ‘return’ In my head I think that boost-lambda works mainly with functors, so since return statement it ...
You cannot use return instruction inside lambda expression. Use constructions like if_then_else_return. They offer syntax that allows producing results. But in your case return is not even required, just throw it away.
3,310,284
3,310,373
How many characters does string class in c++ support?
Possible Duplicate: Maximum length of a std::basic_string<_CharT> string I would like to know how many characters does string class in c++ support. thanks..
std::string s; s.max_size(); That should tell you what that max size is.
3,310,290
3,310,544
Null check on a COleVariant
Is it possible to do a null check on a COleVariant or at the very least check if it's type is set to VT_NULL? I see that there is a ChangeType() method but was hoping I could somehow figure out what the current type was before I attempt to change the type as changing from VT_NULL to VT_INT throws a type mismatch.
Check the vt member.
3,310,337
3,310,425
difference between "long" and "long int", abs & labs
This is probably just an inconsistency of notation at cplusplus.com, but is there a difference between "long int" and "long" types in C++? cplusplus.com says that abs takes inputs of types "int" and "long", whereas labs uses "long int". I assume that this is basically a typo. If so, then is the only difference betwe...
There is no difference between long and long int. The reason we have abs(long) and labs(long) (while both are equivalent) is that labs() is a remnant of the C library. C doesn't have function overloading, so function abs() can only take one type (int) and the long one has to be called differently, hence labs.
3,310,350
3,310,477
Mutex protection for Singleton resources in multithreaded env
I have a server listening on a port for request. When the request comes in, it is dispatched to a singleton class Singleton. This Singleton class has a data structure RootData. class Singleton { void process(); void refresh(); private: RootData mRootData; } In the class there are two functions: process: ...
1] If the class is a singleton and mRootData is inside that class, is the Mutex gaurd really necessary? Yes it is, since one thread may call process() while another is calling refresh(). 2] Should i protect the i) data structure OR ii) function accessing the data structure. Mutex is meant to protect a common code p...
3,310,404
7,303,360
QuickTime component with Xcode 3.2: C++ compilation errors
I'm trying to compile the Xiph QuickTime component Xcode project on OS X. It depends on a number of libraries such as libflac and Theora; all of those dependencies appear to be C code which all compiles nicely with the 10.5 SDK. However, when it comes to compiling the component itself, I get a number of errors, mostly ...
Track data type is used in QuickTime framework which does not work in 64 bit architecture. To compile the code you need to use 32-bit Intel architecture in your project settings. You should have no problems with compiling it with 10.5 and 10.6 SDKs.
3,310,501
3,310,785
how to bind one function to other
I have a function A that accepts a predicate function as its argument. I have another function B and it takes a char and returns an int, and a function C that accepts int and returns a bool. My question is how to bind B and C to pass it to function A. Something like: A(bindfunc(B,C)) I know boost::bind works but i ...
As a simple workaround for the lack of a compose higher order function in std: template <typename F1, typename F2> struct composer : std::unary_function < typename F2::argument_type, typename F1::result_type > { composer(F1 f1_, F2 f2_) : f1(f1_), f2(f2_) {} typename F1::result_ty...
3,310,737
8,741,626
Should we pass a shared_ptr by reference or by value?
When a function takes a shared_ptr (from boost or C++11 STL), are you passing it: by const reference: void foo(const shared_ptr<T>& p) or by value: void foo(shared_ptr<T> p) ? I would prefer the first method because I suspect it would be faster. But is this really worth it or are there any additional issues? Could yo...
This question has been discussed and answered by Scott, Andrei and Herb during Ask Us Anything session at C++ and Beyond 2011. Watch from 4:34 on shared_ptr performance and correctness. Shortly, there is no reason to pass by value, unless the goal is to share ownership of an object (eg. between different data structure...
3,310,740
3,310,859
no matching function for call to ‘Gtk::Main::run(window (&)())
I guess I'm not understanding something about C++: I have this code: #include "window.h" int main(int argc, char* argv[]) { Gtk::Main kit(argc, argv); window win(); Gtk::Main::run(win); return EXIT_SUCCESS; } 'window' is a class that inherits from Gtk::Window with an empty constructor. When I try to...
Because window win(); is the declaration of a function taking no parameters and returning a window. (Hence the error saying no matching call for window (&)(), which is that type.) This is known as the "Most Vexing Parse."
3,310,753
3,310,820
problem writing a simple STL generic function
I'm self-learning how to create generic functions using iterators. As the Hello World step, I wrote a function to take the mean in the given range and returns the value: // It is the iterator to access the data, T is the type of the data. template <class It, class T> T mean( It begin, It end ) { if ( begin == end...
You can use iterator_traits<It>::difference_type instead of int to be sure that it doesn't overflow. This is the type returned by std::distance. Your compilation error is because the compilator cannot determine the type T This is because the compilator looks only at the function's declaration first. And if you look o...
3,310,910
3,310,948
Method resolution order in C++
Consider the following class hierarchy: base class Object with a virtual method foo() an arbitrary hierarchy with multiple inheritance (virtual and non-virtual); each class is a subtype of Object; some of them override foo(), some don't a class X from this hierarchy, not overriding foo() How to determine which method...
There is no MRO in C++ like Python. If a method is ambiguous, it is a compile-time error. Whether a method is virtual or not doesn't affect it, but virtual inheritance will. The algorithm is described in the C++ standard §[class.member.lookup] (10.2). Basically it will find the closest unambiguous implementation in th...
3,310,928
3,311,052
What's the fastest way to generate a random sequence from a list of data?
Let's say that I have a list of data: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} where n = 10 elements I'd like to randomly choose k elements of this set to form a sublist, say k = 5. In that case, I could end up with a sublist that looks like {9, 3, 5, 2, 7} I could accomplish this by: Randomly determining an offset within the l...
Or you could accomplish this by: Randomly determining an offset within the list, between 0 and the current size of the list. Appending that element to your sublist. Repeat until the sublist is probably long enough to contain the right number of elements. For example, if you are choosing 10 out of 1,000,000 elements a...
3,310,959
3,310,999
Binding specific threads to specific processor cores
I've word a bit with parallel processing in college and now I'm trying to get better at it. I can write code that can run in parallel and then start up threads, but after that I loose control over what the threads do. I would like to know how I can control the threads to things like for example bind a specific thread t...
I'm answering in Java perspective: That's not possible. The best what you can control is the thread priority. To force Java to run on certain CPU/core, you have to do it in a platform specific way. In Windows for example, you can do that in the task manager by locating the process in the Processes tab, rightclicking th...
3,311,006
3,311,031
Strange C++ exception "definition"
A student of mine submitted some C++ code similar to the following one. The code compiles and runs, but the throw statement produces the following message: terminate called after throwing an instance of 'int' If I make the function void the compiler complains invalid use of ‘void’ on the line that contains the thro...
It calls the function: MyException(), then throws the returned int. A more complete example: struct foo { int bar(void) const { return 123456789; } void baz(void) const { throw bar(); } }; int main(void) { try { foo f; f.baz(); // throws exception of typ...
3,311,321
3,311,377
Reading in Intel Hex file for sorting C++
I need to read in an Intel Hex file which looks something like this: :0300000002F8D42F :07000300020096000000005E :07000B000200B50000000037 :030013000200D414 :03001B000200F3ED (Yes, some lines are missing and sometimes 1 line only contains 1 byte) The : is the start code First 2 bytes is the byte count Next 4 are t...
I would suggest a Dictionary<RT, byte[]>, and just use a single flat array. Then stride through that array calculating checksums and building the output lines, if all bytes in the line were 0xFF then you can skip appending that line to your output. Maybe Dictionary<RT, List<byte>> if you can't predict the size of each...
3,311,341
3,311,368
Nested template possibilities
Is the following valid?: template<typename T> class C { C1<C2<T>> someMember; };
Well, you'd need to do something with the type, either make it a typedef or member, but yes: template <typename T> struct C1 {}; template <typename T> struct C2 {}; template <typename T> struct C { typedef C1<C2T> > type; // note the space! }; >> is actually the right shift operator, so you need a space in there...
3,311,388
3,312,315
How to speed up offscreen OpenGL rendering with large textures on Win32?
I'm developing some C++ code that can do some fancy 3D transition effects between two images, for which I thought OpenGL would be the best option. I start with a DIB section and set it up for OpenGL, and I create two textures from input images. Then for each frame I draw just two OpenGL quads, with the corresponding im...
It sounds like rendering to a DIB is forcing the rendering to happen in software. I'd render to a frame buffer object, and then extract the data from the generated texture. Gamedev.net has a pretty decent tutorial. Keep in mind, however, that graphics hardware is oriented primarily toward drawing on the screen. Capturi...
3,311,399
3,311,450
Iterate std::list<boost::variant>
How would you check for the object type when looping std::list? class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::varia...
From boost's own example: void times_two( boost::variant< int, std::string > & operand ) { if ( int* pi = boost::get<int>( &operand ) ) *pi *= 2; else if ( std::string* pstr = boost::get<std::string>( &operand ) ) *pstr += *pstr; } i.e. Using get<T> will return a T*. If T* is not nullptr, then...
3,311,421
3,311,797
On the initialization of std::array
Let's say you have a c++0x std::array member of a template class and you want to initialize it by means of a constructor that takes a couple of iterators: template <typename Tp, size_t N> class Test { public: template <typename Iterator> Test(Iterator first, Iterator last) { if (std::distance(first...
No. std::array is an aggregate, so you get no special functionality like constructors taking iterators. (This actually surprises me, with the introduction of std::initializer_list I see no harm in making other useful constructors. Perhaps a question is in store.) This means the only way to use iterators to copy data in...
3,311,509
3,311,919
Fancy way to read a file in C++ : strange performance issue
The usual way to read a file in C++ is this one: std::ifstream file("file.txt", std::ios::binary | std::ios::ate); std::vector<char> data(file.tellg()); file.seekg(0, std::ios::beg); file.read(data.data(), data.size()); Reading a 1.6 MB file is almost instant. But recently, I discovered std::istream_iterator and wante...
You should compare apple-to-apple. Your first code read unformatted binary data because you use the function member "read". And not because you use std::ios_binary by the way, see http://stdcxx.apache.org/doc/stdlibug/30-4.html for more explication, but in short : "The effect of the binary open mode is frequently misun...
3,311,528
3,311,597
Could Bjarne make mistake? (while explaining templates), or I still do not understand?
Guys, I'm doing excercises from "The C++ Programming Language 3rd ed." and on page 340 there is an example of function: template <class T, class C = Cmp<T> > // Here is a default argument // But as far as I'm concerned it's illegal to have a default argument in // a function template int compare (const String<...
Yes, the book is wrong in this case. It is indeed illegal to use default template arguments in function template declarations. You can find the reference to that issue here http://www2.research.att.com/~bs/3rd_issues.html
3,311,563
3,312,337
Do all C++ compilers generate C code?
Probably a pretty vague and broad question, but do all C++ compilers compile code into C first before compiling them into machine code?
Because C compilers are nearly ubiquitous and available on nearly every platform, a lot of (compiled) languages go through this phase in their development to bootstrap the process. In the early phases of language development to see if the language is feasible the easiest way to get a working compiler out is to build a ...
3,311,633
3,311,640
Nested templates with dependent scope
What is dependent scope and what is the meaning of typename in the context of the following error? $ make g++ -std=gnu++0x main.cpp main.cpp:18:10: error: need 'typename' before 'ptrModel<std::vector<Data> >::Type' because 'ptrModel<std::vector<Data> >' is a dependent scope make: *** [all] Error 1 /* * main.cpp */...
The compiler told you exactly what to do. Write typename before ptrModel<std::vector<Data> >::Type, like so: typedef typename ptrModel<std::vector<Data> >::Type Type; The reason for this requirement is that the compiler doesn't at this point know whether ptrModel<std::vector<Data> >::Type describes a member variable ...
3,311,641
56,987,602
C++ Exception Throw/Catch Optimizations
It seems to me that if you have some C++ code like this: int f() { try { if( do_it() != success ) { throw do_it_failure(); } } catch( const std::exception &e ) { show_error( e.what() ); } } The C++ compiler should be able to optimize the throw and catch into almost a simple goto. However, it se...
I think the accepted answer is quite uninformative if not wrong, so even after so many years I feel the need to offer a proper answer. Speculating on why the compiler implementors chose to not put effort on any particular feature is just, well... speculation. The fact that exceptions are thrown only in exceptional cir...
3,311,737
3,311,840
C++ cross platform for processes: is POCO lib good? other alternatives?
I would like to use some cross platform C++ library for starting, stopping and getting standard output for processes. I found and I would like to use C++ POCO libraries: are these good? What's the best alternatives? I use Boost and they have Boost Process, but is not part of the official release and AFAIK it won't be n...
I don't have any direct experience with the Processes lib in POCO but I'm a big fan of the project in general and the networking and threading libs in particular. Works great under Windows (MinGW & VS), OS X, and Linux.
3,311,874
3,311,884
Basic Object Oriented inheritance
Consider the following source code. I have two classes CBar and CFoo. CFoo inherits from CBar. The output of this source code is Bar Foo Bar I was expecting Bar Foo Foo Where did I go wrong? What I was thinking was that since the CFoo object has a Speak function that overrides the CBar speak function. When I c...
In C++, you need to use virtual to enable polymorphism. Otherwise, all Speak() is doing in CFoo is hiding Speak() in CBar. class CBar { public: virtual void Speak() { // Note virtual keyword printf(" Bar \n"); } void DoStuff() { this->Speak(); } };...
3,311,914
3,311,950
Arrays of function pointers as members of classes
Can I have, as a private member of a class, an array of function pointers? Something like, class MyClass { public: //public stuff private: void (*specficFunctions[16]) (void); } I specifically don't want to use functors or functionoids.
Yes, though you usually want to use a typedef to keep the syntax a bit more manageable: class MyClass { typedef void (*fptr)(void); fptr SpecificFunctions[16]; }; Note, however, that these are pointers to global functions, not member functions.
3,312,030
3,312,053
Why am I getting an error when I try to use my structure?
I have a structure Defined in the Header file for a class i am working in, and i am trying to use the Struct in one of the methods of the class. It looks basically like this: struct example { double a; int b; ... }; in the header above my class definition, and then in the cpp file, i have: void examplec...
What about allocating the memory for your structure ? something like : example* teststruct = new example; teststruct->a = 0;
3,312,031
3,312,507
C++ "smart pointer" template that auto-converts to bare pointer but can't be explicitly deleted
I am working in a very large legacy C++ code base which shall remain nameless. Being a legacy code base, it passes raw pointers around all over the place. But we are gradually trying to modernize it and so there are some smart pointer templates as well. These smart pointers (unlike, say, Boost's scoped_ptr) have an ...
The Standard says The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the orig...
3,312,085
3,312,149
Cleaner way to convert from CStringW to std::string?
I figured out a somewhat convoluted way to convert a CStringW to a std::string, but I was wondering if there's a cleaner way than: CStringW cwstr; std::wstring stdwstr = cwstr; std::string stdstr = CW2T(stdwstr.c_str());
You can cut out the intermediate std::wstring: CStringW cwstr; std::string stdstr = CW2A(cwstr); Also note that you want the CW2A macro for correctness. CW2T converts to a TCHAR string, so the code you posted would only compile for an ANSI build (where TCHAR is char).
3,312,192
3,312,515
Unable to dispose of C# COM object
I have a C# class that I've made ComVisible so that it can be used in an unmanaged C++ DLL. The C# class is defined like this: public interface IFSFunction { double GetProcessTime(); } public class Functions : IFSFunction { // Initialization here // Interface function public double GetProcessTime() ...
I'm going to guess you are using a debugging tool that let's you take a look at the managed heap. Like Windbug.exe with sos.dll. Yes, you'll see an instance of the Functions class object after the final Release() call. It is a managed object that follows normal garbage collection rules. It won't be collected until ...
3,312,335
3,312,444
Use C++ constants in C# program
We have a situation where we use a set of third-party unmanaged C++ libraries in our C# (WPF) application, but we also use a subset of their include libraries to build our own unmanaged libraries to use in our application. These libraries produce metadata, which is stored in a database. However, we must replicate some...
I have a solution that you may not consider terribly "clean" but which will work. The problem is that using either an enum or #define preprocessor directives will discard the symbolic name you're using for the constant (like ERR_OUT_OF_MEMORY will really just be some integer). In the C++ code, you could define a funct...
3,312,486
3,312,735
How to print an object of unknown type
I have a templatized container class in C++ which is similar to a std::map (it's basically a thread-safe wrapper around the std::map). I'd like to write a member function which dumps information about the entries in the map. Obviously, however, I don't know the type of the objects in the map or their keys. The goal ...
You can provide a templated << operator to catch the cases where no custom output operator is defined, since any more specialized versions will be preferred over it. For example: #include <iostream> namespace detail { template<typename T, typename CharT, typename Traits> std::basic_ostream<CharT, Traits> & ...
3,312,513
3,312,638
On a disadvantage of exceptions in C++
I was reading Google C++ Style Guide, and got confused in the Exceptions part. One of the cons of using it, according to the guide is: Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid r...
"writes to persistent state" mean roughly "writes to a file" or "writes to a database". "into a 'commit' phase." means roughly "Doing all the writing at once" "perhaps where you're forced to obfuscate code to isolate the commit" means roughly "This may make the code hard to read" (Slight misuse of the word "obfuscate...
3,312,768
3,312,795
Error in template function (using Boost.Tuples)
#include <list> #include <boost/tuple/tuple.hpp> template<class InputIterator> void f(InputIterator it) { typedef boost::tuple<typename InputIterator::value_type, int> Pair; std::list<Pair> paired; typename std::list<Pair>::const_iterator output; for(output=paired.begin(); output!=paired.end(); ++outpu...
Because get is a function template and the type of output is dependent upon the template parameter InputIterator, you need to use the template keyword: output->template get<1>(); The Comeau C++ Template FAQ has a good description of why this is necessary.
3,313,023
3,313,035
Why do the characters ÌÌÌÌ get stuck onto the begining of my strings?
I have been developing some computer vision tools with openCV, but every time that I pass a string into an openCV function, the characters ÌÌÌÌ get tagged onto the beginning. At first this was just annoying, but now I am trying to use openCV's fileStorage tools and the ÌÌÌÌ characters are making my file names unreadabl...
Given that ÌÌÌÌ = 0xCCCCCCCC, it seems the library does not expect a 4-byte member before the string member, e.g. // Provided. struct something { ... void* some_pointer; // uninitialized variables are filled with 0xCC in debug mode. char the_actual_content[1234]; ... } // But the library wants struct somet...
3,313,036
3,313,070
Mobile physics engine
I'm looking to use a physics engine for a 3D mobile game that I'm working on. I'd like to use a library that supports fixed point math and preferably coded in C++. Any recommendations?
The two major open source players are: Bullet ODE I don't think either of them allow for fixed point types, however. Both are written in C++, although the ODE API is in C.
3,313,104
3,313,171
Possible compilation errors in C++
In C++, what kind of compilation errors might I run into while using function overloading, and when might these occur?
This website has a couple listed, though I think your question will probably get closed as not a real question: http://net.pku.edu.cn/~course/cs101/resource/CppHowToProgram/5e/html/ch06lev1sec17.html Creating overloaded functions with identical parameter lists and different return types is a compilation error. A ...
3,313,233
3,313,265
Linked list head double pointer passing
I have seen this in some book/ tutorial. When you pass in the head pointer (of linked list) into a function, you need to pass it as a double pointer. For eg: // This is to reverse a linked list where head points to first node. void nReverse(digit **head) { digit *prev=NULL; digit *curr=*head; digit *next; ...
This is very C-like code, not C++. Basically, when something is passed by-value the function operates on a copy of the data: void foo(int i) { i = 5; // copy is set to 5 } int x = 7; foo(x); // x is still 7 In C, you instead pass a pointer to the variable, and can change it that way: void foo(int* i) { *i = 5...
3,313,299
3,313,798
Width as a variable when using fscanf
I am trying to read in a certain portion of a file and that amount of data is different per line but I know how how many bytes of info I want. Like this: 5bytes.byte1byte2byte3byte4byte5CKSum //where # of bytes varies for each line (and there is no period only there for readability) Actual data: 05AABBCCDDEE11 0...
Unfortunately, no, there's no modifier like '*' for printf that causes scanf to get its field width or precision from a variable. The closest you can come is dynamically creating the format string: char format[8]; sprintf(format, "%%%dX", width); fscanf(in_file, format, &iData);
3,313,301
3,313,321
Complexity of STL max_element
So according to the link here: http://www.cplusplus.com/reference/algorithm/max_element/ , the max_element function is O(n), apparently for all STL containers. Is this correct? Shouldn't it be O(log n) for a set (implemented as a binary tree)? On a somewhat related note, I've always used cplusplus.com for questions whi...
It's linear because it touches every element. It's pointless to even use it on a set or other ordered container using the same comparator because you can just use .rbegin() in constant time. If you're not using the same comparison function there's no guarantee that the orders will coincide so, again, it has to touch ev...
3,313,354
4,661,179
template self friendship
template < typename T > struct test { template < typename U > friend struct test<U>; }; int main() {} This is perfectly valid code, no? I ask because MSVC++ 2010 fails to compile it. Not the first time templates have confuzled the MS compiler though. As far as I can tell from books, websites, and such it shoul...
The correct syntax is: template < typename T > struct test { template < typename U > friend struct test; // no <U> }; int main() {}
3,313,428
3,313,585
When catching an exception's parameter by value, what is the order in which the destructors are called?
In the following code, what is the order in which the destructors of b, q and e are called, and which is called before handling the exception. (The "cout..." parts are leftover for the original question) #include <iostream> using namespace std; class A { public: A(int arg) : m(arg) { cout << "A::A(int) " <<...
q's desctructor is called first because it is destroyed as the first part of stack unwinding (local objects in the inner most scope are destroyed first), then b's destructor is called, also as part of stack unwinding. Both are destroyed before the catch block is even entered. Stack unwinding happens before the exceptio...
3,313,479
3,313,638
std::tuple get() member function
boost::tuple has a get() member function used like this: tuple<int, string, string> t(5, "foo", "bar"); cout << t.get<1>(); // outputs "foo" It seems the C++0x std::tuple does not have this member function, and you have to instead use the non-member function form: std::get<1>(t); which to me looks uglier. Is there a...
From C++0x draft: [ Note: The reason get is a nonmember function is that if this functionality had been provided as a member function, code where the type depended on a template parameter would have required using the template keyword. — end note ] This can be illustrated with this code: template <typename T> struct ...
3,313,527
3,313,543
Does allowing a std::fstream to be destroyed close the associated file?
I'm wondering if I need an RAII wrapper around std::fstream....
No you don't. It closes the file. § 27.8.1.2: virtual ˜basic_filebuf(); Effects: Destroys an object of class basic_filebuf. Calls close(). (which is contained as an object within std::fstream (§ 27.8.1.11), thus being destructed when the fstream is destructed).
3,313,581
3,313,700
Runtime process memory patching for restoring state
I'm looking for a method for storing the process memory, and restore it later at certain conditions. ... Actually I've read questions about it... It seems a big challenge! So, let's analyse: The application is a distributed one, but many processes are stateless (request their state to a centralized server). Processes u...
ReadProcessMemory is for reading the memory of another process. Inside of a process, it's unnecessary -- you can just dereference a pointer to read memory within the same process. To find the blocks of memory in a process, you can use VirtualQuery. Each block will be tagged with a state, type, size, etc. Here's some co...
3,313,625
3,313,652
Why does my setup.py script give this error?
So I have a C++ class that I made python wrappers for, and I made a setup.py file to compile it in order to use it in python. When I try to run python setup.py install I get the following error: lipo: can't create output file: build/temp.macosx-10.5-fat3-2.7/../tools/transport-stream/TransportStreamPacket_py.o (No such...
Your problem is the leading '..' in the source definitions. Distutils uses the names of the source files to generate names of temporary and output files, but doesn't normalize them. Reorganize your source tree (or move the setup.py file) so you don't need to reference '../tools/...'
3,313,754
3,314,340
static abstract methods in c++
I have an abstract base class class IThingy { virtual void method1() = 0; virtual void method2() = 0; }; I want to say - "all classes providing a concrete instantiation must provide these static methods too" I am tempted to do class IThingy { virtual void method1() = 0; virtual void method2() = 0; static vir...
The problem that you are having is partly to do with a slight violation a single responsibility principle. You were trying to enforce the object creation through the interface. The interface should instead be more pure and only contain methods that are integral to what the interface is supposed to do. Instead, you can ...
3,313,777
3,313,949
Returning COM object to JScript
I am trying to pass a COM object from an ActiveX component to JScript. So far I have tried the following method of doing so: STDMETHODIMP CHSNetwork::CreateIPPPacket(VARIANT ** ppv) { IIPPacket *iipp; HRESULT hr = CoCreateInstance(CLSID_IPPacket, NULL, CLSCTX_ALL, IID_IIPPacket, (void **)&iipp); if(SUCCEEDE...
Ah. I got it. I needed to pass a VARIANT * not a VARIANT **. I guess I still get confused by pointers-to-pointers as it relates to return values with COM. Thus the correct code is: STDMETHODIMP CHSNetwork::CreateIPPPacket(VARIANT * ppv) { // TODO: Add your implementation code here IIPPacket *iipp; HRESULT h...
3,313,805
3,313,997
converting an integer to a std::string accepted by an std::pair
I have this function that converts an integer to a std::string: std::string intToStr(const int n) { stringstream ss; ss << n; return ss.str(); } It's worked well so far, but now I'm trying to construct a string to put into a std::pair, and I'm having some trouble. Given an integer variable hp and a functio...
The reason that this fails: if(verbose) string ratio = intToStr(hp) + "/" + intToStr(maxHP()); // the block of the if is now over, so any variables defined in it // are no longer in scope is that a variable's scope is limited to the block it is defined in.
3,314,010
3,314,030
Should small simple structs be passed by const reference?
I have always been taught that non-primitive types should be passed by const reference rather than by value where possible, ie: void foo(std::string str);//bad void foo(const std::string &str);//good But I was thinking today that maybe actually some simple user defined types may actually be better passed by value eg: ...
Yes, simple objects should be passed by value. The line has to be drawn according to the architecture. If in doubt, profile.
3,314,512
3,314,585
Compile error when attemping to get value of QSqlQuery?
Just trying to mess around with Qt and SQLite to get familiar with how things work- I haven't really done DB programming since my vb6 days, so please be easy ;] I'm just trying to get the result of a query and I'm trying to follow some examples I found online (namely this one). The process seems simple enough: create t...
Basically, the type is declared but not defined, like this: struct QVariant; Once you try to use it, it needs to be defined, like this: struct QVariant { // stuff goes here }; The error is telling you it's incomplete (declared but not defined), and therefore not usable. You should include the header <QVariant> to...
3,314,672
3,314,684
Why do we use templates instead of functions?
Just looking for some good reasons so i could start learning about them :/
To avoid repeating code that would be otherwise identical except for different types. Sometimes you simply can't rely on implicit conversion or promotion and you can't stuff everything into an object hierarchy.
3,314,944
3,314,994
How is dynamic_cast typically implemented?
Is the type check a mere integer comparison? Or would it make sense to have a GetTypeId virtual function to distinguishing which would make it an integer comparison? (Just don't want things to be a string comparison on the class names) EDIT: What I mean is, if I'm often expecting the wrong type, would it make sense to ...
The functionality of the dynamic_cast goes far beyond a simple type check. If it was just a type check, it would be very easy to implement (something like what you have in your original post). In addition to type checking, dynamic_cast can perform casts to void * and hierarchical cross-casts. These kinds of casts conce...
3,315,185
3,315,199
C++: pass-by-reference and the const keyword
I have a question regarding the passing of a map by reference. Let's consider the following piece of codes: void doNotChangeParams(const map<int, int>& aMap){ if (aMap.find(0) != aMap.end()){ cout << "map[0] = " << aMap[0] << endl; } } and I'm having a map myMap and make a call like this: doNotChange...
The [] operator on std::map is non-const. This is because it will add the key with a default value if the key is not found. So you cannot use it on a const map reference. Use the iterator returned by find instead: typedef map<int, int> MyMapType; void doNotChangeParams(const MyMapType& aMap){ MyMapType::const_i...
3,315,217
3,315,276
What is the purpose of this code?
I am struggling to understand why the initialization of pprocessor, below, is written like this: class X { ... private: boost::scoped_ptr<f_process> pprocessor_; }; X:X() : pprocessor_( f_process_factory<t_process>().make() ) //why the factory with template {...} instead of just writing X:X() : pprocessor_( new ...
As it is, it seems kinda pointless, but I can think of a few possible uses that aren't shown here, but may be useful in the future: Memory management: It's possible that at some point in the future the original author anticipated needing a different allocation scheme for t_process. For example, he may want to reuse o...
3,315,310
3,315,374
What is the C version of RMI
I have a set of functions in C/C++ that I need to be available to accept calls and return values to C/C++ code in a remote location, similar to RMI on the java platform. With RMI the Java methods are set up through the rmiregistry and remain available in memory to accept requests. I'm looking for similar functionality ...
Is this type of scenario that CORBA was intended for and if so, is this still the best technology to use or are there better options out there. Yes, this is what CORBA was intended to solve. Whether it's "best" is subjective and argumentative. :) I can say, from my personal experience, I don't miss my short experie...
3,315,383
3,315,513
Compound argument declaration
To make my code more concise, can I do something like int f(int const x, y, z), g(int const x, y, z); to declare functions f and g which each take three int const arguments? Edit: Perhaps here is a better example: int f(int const a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z); How would...
Using Boost preprocessor, and considering you don't care to describe the function arguments one by one (but isn't that the point of your question), you can use the following trick : #include <boost/preprocessor/repetition/enum_params.hpp> int f( BOOST_PP_ENUM_PARAMS(26, int const arg) ); But don't forget that the who...
3,315,461
3,315,471
Evenly distributed dashed lines with OpenGL?
I notice that drawing dashed lines with GL will not make them even apart unless each vertex is equidistant from the last. Is there a way to simply make the whole path dashed evenly regardless of the distance between each point? Thanks
I'm guessing you're drawing GL_LINES rather than GL_LINE_STRIPs or GL_LINE_LOOPs. With the latter, the individual segments are connected and the stipple pattern is continuous from one to the next.
3,315,507
3,318,513
module machine type 'THUMB' conflicts with target machine type 'ARM'
I had a windows mobile application running for ARMV4 (Pocket PC 2003) We got a new device XXXCE6 (ARMV4I), we need to compile the application for it, we followed these steps: install the Device SDK Build-> configurartion manager choose NEW from active solution platform for New Solutin platform we have chosen XXXCE6 (A...
Adding a new configuration never works - it's something the tools team I think never actually tried. It didn't work in eVC 3.0 or 4.0 and still doesn't in Studio. Create a new project using the app wizard, selecting your SDK. When you are done, just use "Add Existing" to add all of your code in. BTW, your app can pro...
3,315,582
3,315,656
Overload operator == for STL container
I'm trying to remove a class object from list<boost::any> l l.remove(class_type); I tried writing something like this as a member function bool operator == (const class_type &a) const //not sure about the arguments { //return bool value } How would you write an overload function to remove an object of class from a...
While your signature for operator== looks fine, overloading it for class_type isn't enough as boost::any doesn't magically use it. For removing elements however you can pass a predicate to remove_if, e.g.: template<class T> bool test_any(const boost::any& a, const T& to_test) { const T* t = boost::any_cast<T>(&a); ...
3,315,857
3,685,633
Question about how to general a bezier curve by inputing several points
i want to generate a bezier curve pass through several points i input by mouse.These points are more than four,can anyone help me and give me some suggestions about how to implent it? More thanks. Good luck!
You have to solve the distance between points along the curve first to get your u & v. Generally, the shortest arc lengths between points approx. the best curve. p0 and p3 are the endpoints; f and g are two points along the curve. d1 is distance between p0 and f; d2 between f and g; d3 between g and p3. Solving for con...
3,315,963
3,413,182
Serialization tree structure using boost::serialization
I have to serialize libkdtree++ in my program, the tree structures are briefly described as following: struct _Node_base { _Node_base * _M_parent, *_M_left, * _M_right; template<Archive> serialize(Archive &ar, const unsigned int version) { ar & _M_left & _M_right; } } template<typename V> struct _Node : p...
The following solution for libkdtree++ & boost::serialization seems work: // KDTree::_Node friend class boost::serialization::access; template<class Archive> //void serialize(Archive & ar, const unsigned int version) void save(Archive & ar, const unsigned int version) const { ar.register_type(static_cast< _Link_type>...
3,316,102
3,420,491
Who knows how to use the mc.exe (Message Compiler)?
I am trying to use the mc.exe to make message files for my event log writing program. But even the sample message file provided by the Microsoft won't compile. Who knows how to write a message file that could be compiled by mc.exe? EDIT: The error message I got is : msgs.mc(1) : error : expected keyword - ?? Edit 2: P...
Problem solved. The mc.exe can only support Unicode or ANSI encoded source file. My file is encoded as UTF8. That's it. Thanks guys.
3,316,130
3,316,515
changing float type to short but with same behaviour as float type variable
Is it possible to change the float *pointer type that is used in the VS c++ project to some other type, so that it will still behave as a floating type but with less range? I know that the floating point values never exceed some fixed value in that project, so I want to optimize the program by memory it uses. It do...
There is a standard 16-bit floating point format described in IEEE 754-2008 called "binary16". It is specified as a format to store floating point values with reduced precisions. There is almost no compiler support for that yet (I think GCC supports it for certain ARM platforms), but it is quite easy to roll your own r...
3,316,195
3,316,268
Xcode not showing console output; How do you flush the console?
I have a simple C++ program that uses cout and printf to log stuff and it is only showing at the end when the program is closed but if I'm stepping through the program using debug nothing is shown. Did anybody have this problem?
If you're practicing c try fflush, if c++ try cout << endl; each time you want to print.
3,316,201
3,316,224
Print longest string duplicated M times
here is code which prints longest string duplicated M times #include <iostream> #include <stdlib.h> #include <string.h> #include <stdio.h> using namespace std; #define M 1 #define MAXN 5000000 char c[MAXN],*a[MAXN]; int pstrcmp( char **p,char **q){ return strcmp(*p,*q) ;} int comlen(char *p,char *q){ int i=0;...
Change int pstrcmp( char **p,char **q){ return strcmp(*p,*q) ;} to int pstrcmp(const void *p, const void *q) { return strcmp(*reinterpret_cast<const char**>(p), *reinterpret_cast<const char**>(q)); }
3,316,261
3,316,388
prevent long running averaging from overflow?
suppose I want to calculate average value of a data-set such as class Averager { float total; size_t count; float addData (float value) { this->total += value; return this->total / ++this->count; } } sooner or later the total or count value will overflow, so I make it doesn't remember the tot...
Aggregated buckets. We pick a bucket size that's comfortably less than squareRoot(MAXINT). To keep it simple, let's pick 10. Each new value is added to the current bucket, and the moving average can be computed as you describe. When the bucket is full start a new bucket, remembering the average of the full bucket. We c...
3,316,335
3,316,419
error C2664 - code compiles fine in VC6; not in VS 2010
I have a typedef, a class with a member vector using that type and then a method using std::<vector>::erase(). #typedef DWORD WordNo_t; class CWordList : public CObject { public: WordNo_t* begin() { return m_Words.begin(); } WordNo_t* end() { return m_Words.end(); } void truncate (WordNo_t *Ptr) { if (Ptr == end()...
I'm surprised begin and end are even compiling, they shouldn't. std::vector (and friends) use iterators, not pointers. (Though they are intended to act similarly.) In any case, erase takes an iterator, not a pointer. Because vectors are contiguous, you can make utility functions as such, though: template <typename T, t...
3,316,447
3,316,458
passing pointers to function that takes a reference?
In C++, when you have a function that takes a reference to an object, how can you pass an object pointer to it? As so: Myobject * obj = new Myobject(); somefunc(obj); //-> Does not work?? Illegal cast?? somefunc(Myobject& b) { // Do something }
Just dereference the pointer, resulting in the lvalue: somefun(*obj);
3,316,514
3,316,551
The purpose behind empty struct?
Declarations of auto_ptr from C++ Standard Library namespace std { template <class Y> struct auto_ptr_ref {}; template <class X> class auto_ptr { public: typedef X element_type; // 20.4.5.1 construct/copy/destroy: explicit auto_ptr(X* p =0) throw(); auto_ptr(auto_ptr&) t...
Google search for "auto_ptr_ref" reveals this detailed explanation. I don't quite get that explanation, but looks like it is for the following. Without that trick you could pass an auto_ptr into a function that would get ownership of the object and assign your variable to a null pointer. With the extra class trick abov...
3,316,534
3,319,402
how do i shot stdafx.h?
I am using Visual Studio 2010 to make a 3D model in C++ and OpenGL. I started a project on my home pc, and then decided to put it in a repository, so that I could get the code for development on my laptop and not have to keep transferring files between the two computers (and also just to get some practice at using sour...
What I have situations where an application can't find a file in the place where I think it should be looking, I always run ProcMon ( http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx ). 99 times out of 100, you'll find it's doing one of the following: Finding the wrong file somewhere else first Not lookin...
3,316,562
3,316,811
const pointer assign to a pointer
Why can I not do this: char* p = new char[10]; void SetString(char * const str) { p = str; } SetString("Hello"); I have a const pointer to a char, why can I not assign the const pointer to another pointer? It just seems illogical, as by assigning it to another pointer, you are not essentially violating the cons...
There is difference between constant pointer and pointer to constant. Constant pointer is a pointer (a number - memory address) that cannot be changed - it always point to the same object given via initialization: int * const const_pointer = &some_int_var; // will be always pointing to this var const_pointer = &some_ot...
3,316,573
3,317,316
C++0x: iterating through a tuple with a function
I have a function named _push which can handle different parameters, including tuples, and is supposed to return the number of pushed elements. For example, _push(5) should push '5' on the stack (the stack of lua) and return 1 (because one value was pushed), while _push(std::make_tuple(5, "hello")) should push '5' and ...
I solved the problem with some hacks. Here is the code: template<typename... Args, int N = sizeof...(Args)> int _push(const std::tuple<Args...>& t, std::integral_constant<int,N>* = nullptr, typename std::enable_if<(N >= 1)>::type* = nullptr) { return _push(t, static_cast<std::integral_constant<int,N-1>*>(nullptr)) ...
3,316,853
3,316,888
Am I misunderstanding assert() usage?
I was taking a look at the assert() reference page and I got stuck while I read the given example: /* assert example */ #include <stdio.h> #include <assert.h> int main () { FILE * datafile; datafile=fopen ("file.dat","r"); assert (datafile); fclose (datafile); return 0; } In this example, assert is used ...
You're perfectly right sir. This is a poor usage of assert.
3,316,917
3,317,769
Zooming the graphics in Qt
I use QGraphicsView and QGraphicsScene in order to draw graphics. How can I organize zoom-in and zoom-out (during zooming in scrolls should appear and while zooming out scrolls should disappear)?
QGraphicsView::scale(qreal, qreal) e.g. QGraphicsView * view = new QGraphicsView (parent); QGraphicsScene *scene = new QGraphicsScene(); scene->addText("Hello World"); view->setScene(scene); view->show(); view->resize(100,100); // coll from some slot to see the effect view->scale(2,2); //zoom in view->scale(.5,.5)...
3,317,030
3,317,112
easy and portable ping pong communication
is there a way to implement such a communication in C++? use case: my main program calls a function of my external library to process a list. every time the function iterates through the list it sends a ping to the caller. the latter uses the received signal to track progress of the former and sends back a boolean pong...
If it is the whole list you are processing, why not just use a return value from the function call to indicate when the iteration is complete. If you want to continue, call the function again - if not, dont.
3,317,167
3,317,213
What happens when i copy pthread_rwlock_t?
pthread_rwlock t1; pthread_rwlock_wrlock(&t1); pthread_rwlock t2 = t1; what happend? is t2 locked or not?
Nothing special happens. pthread_rwlock_t (not pthread_rwlock, AFAIK) is an opaque C struct. Copying the variable simply copies the struct, byte for byte. At the Pthreads level, copying a pthread_rwlock_t results in undefined behaviour. Don't do it.
3,317,205
3,317,231
using clone(): segmentation fault
I want to use clone to log the current status of my program. It has a lot of loops and I want to keep track of the process without printing the status in each loop iteration. That's why I created this proof-of-concept: #include <iostream> #include <cstdlib> unsigned int i; int log(void*) { std::cout << "LOGGING STA...
The stack argument to clone is a simple void*. Also, the stack grows down on most architectures, so the stack pointer should point to the end of the allocated memory. In any case, you shouldn't use clone directly unless you really need to avoid any dependencies on external libraries. Use the pthreads library instead. I...
3,317,301
3,317,334
C++ - Custom build events
Is there any way to force Clean action as a Post / Pre build event for single project in Visual Studio? Thank you.
Yes, right-click on your project in Solution Explorer and click Properties go to Build events, then Pre-Build Events put del /F /Q $(TargetDir)*.* in command line section.