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,272,708
3,272,731
Does std::vector use the assignment operator of its value type to push_back elements?
If so, why? Why doesn't it use the copy constructor of the value type? I get the following error: /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc: In member functio n `ClassWithoutAss& ClassWithoutAss::operator=(const ClassWithoutAss&)': /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc:238: instantiate d from `void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterato r<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = ClassWithoutAss, _Alloc = std::allocator<ClassWithoutAss>]' /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_vector.h:564: instantia ted from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Class WithoutAss, _Alloc = std::allocator<ClassWithoutAss>]' main.cpp:13: instantiated from here /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc:238: error: non-st atic const member `const int ClassWithoutAss::mem', can't use default assignment operator running g++ main.cpp on the following code: /* * ClassWithoutAss.h * */ #ifndef CLASSWITHOUTASS_H_ #define CLASSWITHOUTASS_H_ class ClassWithoutAss { public: const int mem; ClassWithoutAss(int mem):mem(mem){} ClassWithoutAss(const ClassWithoutAss& tobeCopied):mem(tobeCopied.mem){} ~ClassWithoutAss(){} }; #endif /* CLASSWITHOUTASS_H_ */ /* * main.cpp * */ #include "ClassWithoutAss.h" #include <vector> int main() { std::vector<ClassWithoutAss> vec; ClassWithoutAss classWithoutAss(1); (vec.push_back)(classWithoutAss); return 0; }
The C++03 standard says elements must be copy-constructible and copy-assignable to be used in a standard container. So an implementation is free to use whichever it wants. In C++0x, these requirements are put on a per-operation basis. (In general, elements must be move-constructible and move-assignable.) To get what you want, you should use a smart pointer like shared_ptr (from either Boost, TR1, or C++0x), and completely disable copy-ability: class ClassWithoutAss { public: const int mem; ClassWithoutAss(int mem):mem(mem){} // don't explicitly declare empty destructors private: ClassWithoutAss(const ClassWithoutAss&); // not defined ClassWithoutAss& operator=(const ClassWithoutAss&); // not defined }; typedef shared_ptr<ClassWithoutAss> ptr_type; std::vector<ptr_type> vec; vec.push_back(ptr_type(new ClassWithoutAss(1))); Pointers can be copied just fine, and the smart pointer ensures you don't leak. In C++0x you can do this best with a std::unique_ptr, taking advantage of move-semantics. (You don't actually need shared semantics, but in C++03 it's easiest as it stands.)
3,272,810
3,272,825
question about auto_ptr::reset
please can anybody explain this code from C++ Reference site: #include <iostream> #include <memory> using namespace std; int main () { auto_ptr<int> p; p.reset (new int); *p=5; cout << *p << endl; p.reset (new int); *p=10; cout << *p << endl; return 0; }
auto_ptr manages a pointer. reset will delete the pointer it has, and point to something else. So you start with auto_ptr p, pointing to nothing. When you reset with new int, it deletes nothing and then points to a dynamically allocated int. You then assign 5 to that int. Then you reset again, deleting that previously allocated int and then point to a newly allocated int. You then assign 10 to the new int. When the function returns, auto_ptr goes out of scope and has its destructor called, which deletes the last allocated int and the program ends.
3,272,822
3,272,867
does adding a dummy parameter to constructors of a class to solve calling ambiguity, violate any rule?
take following class and two object definitions: class Rect{ public: enum centimeter; enum meter; Rect(double len,double wid,enum centimeter){ length=(len/100); width=(wid/100); } Rect(int len,int wid,enum meter){ length=len; width=wid; } //rest of implementation private: double length;//in meters double width;//in meters }; Rect obj1(10,5,Rect::centimeter()); Rect obj2(10,5,Rect::meter()); two previous constructors have dummy enum parameters to solve calling ambiguity caused in case these dummy parameters didn't exist. Now in spite of possibility of using named constructors here, if I insist on using these dummy parameters, does this violate any coding rule that I should be aware of ?
STL uses that idiom to differentiate iterator types in lieu of concepts.
3,273,155
3,273,721
Perspective and Bilinear transformations
I'm making a vector drawing application and noticed that Anti Grain Geometry have an example that does exactly what I want. http://www.antigrain.com/demo/index.html then below there is an example on perspective for Win32. I don't understand their cpp file. Based on this example. If I have a bunch of verticies to form an object, like their lion, and then I have 4 verticies as control points, how could I achieve their effect? Ex, what transformation do I apply to each point? Thanks
From that very page you posted, there's a link to the source code. I'll explain the bilinear transformation in http://www.antigrain.com/__code/include/agg_trans_bilinear.h.html The idea here is to find a transformation of the form: output_x = a * input_x + b * input_x * input_y + c * input_y + d output_y = e * input_x + f * input_x * input_y + g * input_y + h The term "bilinear" comes from each of those equations being linear in either of the input coordinates by themselves. We want to solve for the right values of a, b, c, and d. Say you have the reference rectangle r1, r2, r3, r4 which you want to map to (0,0), (1,0), (0,1), (1,1) (or some image coordinate system). For a,b,c,d: 0 = a * r1_x + b * r1_x * r1_y + c * r1_y + d 1 = a * r2_x + b * r2_x * r2_y + c * r2_y + d 0 = a * r3_x + b * r3_x * r3_y + c * r3_y + d 1 = a * r4_x + b * r4_x * r4_y + c * r4_y + d For e,f,g,h: 0 = e * r1_x + f * r1_x * r1_y + g * r1_y + h 0 = e * r2_x + f * r2_x * r2_y + g * r2_y + h 1 = e * r3_x + f * r3_x * r3_y + g * r3_y + h 1 = e * r4_x + f * r4_x * r4_y + g * r4_y + h You can solve this however you like best. (If you're familiar with matrix notation, these are two matrix equations for which the matrix is the same, and then you simply need to find the LU decomposition once, and solve the two unknown vectors). The coefficients are then applied to map the interior of the rectangle to the position in the rectangle. If by any chance you're looking for the inverse transform, that is, if you want to know where a given pixel will land, you simply switch inputs and outputs: For a,b,c,d: r1_x = a * 0 + b * 0 * 0 + c * 0 + d r2_x = a * 1 + b * 1 * 0 + c * 0 + d r3_x = a * 0 + b * 0 * 1 + c * 1 + d r4_x = a * 1 + b * 1 * 1 + c * 1 + d For e,f,g,h: r1_y = e * 0 + f * 0 * 0 + g * 0 + h r2_y = e * 1 + f * 1 * 0 + g * 0 + h r3_y = e * 0 + f * 0 * 1 + g * 1 + h r4_y = e * 0 + f * 0 * 1 + g * 1 + h
3,273,354
3,273,448
Accessing a static member that has the same name as an inner type
I have a few classes that define sequences whose values must be available both at compile-time through a value member and at runtime as an actual instance of the type. So my base types for an arithmetic sequence looks a little like this, template<int A, int D> struct ArithmeticSequence : public Sequence { ArithmeticSequence(VALUE v) : Sequence(v) {} template<unsigned int N> struct VALUE_N : public VALUE { static const int value = A+(D*N); operator int() { return value; } }; }; class Sequence currently just defines an inner class VALUE (currently empty) and a constructor that takes a VALUE, but I will move the operator int() of VALUE_N into VALUE and Sequence will define iterators, etc, further down the line. Now, classes should extend from ArithmeticSequence and define constants for each of the members of the sequence. I've got two methods that I think will work for this, if I don't mind instances of sequences being able to be constructed from members of related sequences (that is, sequences with the same initial value and common difference), I can use typedef: struct mySequence : public ArithmeticSequence<0,1> { mySequence(VALUE val = VALUE_N<0>::value) : ArithmeticSequence(val) {} typedef VALUE_N<0> zeroth; typedef VALUE_N<1> first; // ... }; And if I do, I can extend from VALUE_N: struct mySequence : public ArithmeticSequence<0,1> { mySequence(VALUE val = VALUE_N<0>::value) : ArithmeticSequence(val) {} struct zeroth : public VALUE_N<0> {}; struct first : public VALUE_N<1> {}; // ... }; In both these cases I think I can use mySequence::zeroth::value to get at the value at compile time, and mySequence::zeroth() to get a runtime object. However using the second method causes the compiler confusion as to whether I'm declaring a function or initializing an instance, so I need, mySequence s1 ((mySequence::zeroth())); instead of mySequence s1 (mySequence::zeroth()). Now, I've found that the following is valid, struct mySequence : public ArithmeticSequence<0,1> { mySequence(VALUE val = VALUE_N<0>::value) : ArithmeticSequence(val) {} struct zeroth : public VALUE_N<0> {}; static const zeroth zeroth; struct first : public VALUE_N<1> {}; static const first first; // ... }; But my question (finally) is, what are the rules as to which one I'm accessing at any time? I can use static const int i = mySequence::zeroth::value and, mySequence s1 (mySequence::zeroth), so the right thing seems to happen there, but if I say mySequence::zeroth z instead of treating zeroth as a class it treats it as the variable. This isn't a problem in this case since I don't want people creating new mySequence::zeroth's or any other value, but I think if I don't understand when it will use each one I may let myself in for trouble at a later date. Sorry about the extra long post, and thankyou in advance for your time and patience for anyone who got this far. I'm wondering now if I should have put in all the back story or just simply asked the question, if the concensus is I should have, I'll edit it down. Thanks. Edit. Please note, as I have written it above, using the struct method as opposed to the typedef does not provide any protection against using another "related" sequences members to construct a sequence object, it is needed, I think, however for the last example to work.
The names of enumerators, function and objects hide the names of enumerations and classes that are declared in the same scope. In your case, the data member name hides the name of the struct. You can access the hidden type name by special lookups: The name prior to :: is looked up by ignoring object-, function- and enumerator names. The name used to specify a base class ignores any non-type names. The name specified in an elaborated type specifier ignores object-, function- and enumerator names. Thus, the following elaborated type specifier is valid and refers to the class struct mySequence::zeroth var; Also, note that it is ill-formed when in class scope a member declaration changes the meaning of a name used in that declaration. In your case, let's take static const first first;. The first name will refer to the type, but in the complete scope of mySequence, that name would refer to the data member. The Standard says A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule. Your compiler is not required to diagnose it, which is a phrase meaning that it is effectively undefined behavior (good compilers warn you with something like "member changes meaning of name"). Albeit i doubt that the above rule is intended to apply in this case (as it is worded, it certainly applies though), you can clear the code up by using an elaborated type specifier struct first : public VALUE_N<1> { }; static const struct first first; Notice that you are required to use the elaborated type specifier in the out-of-class definition of the static member. Some compilers allow you to use the injected class name for refering to the type too (GCC did, in the past) const struct mySequence::first mySequence::first; The following uses the injected class name. first appears before :: and ignores the data member. But the compiler has to lookup the name mySequence::first::first to first's constructor and not to its class type const mySequence::first::first mySequence::first;
3,273,430
3,273,699
A boot loader in C++
I have messed around a few times by making a small assembly boot loader on a floppy disk and was wondering if it's possible to make a boot loader in c++ and if so where might I begin? For all I know im not sure it would even use int main(). Thanks for any help.
If you're writing a boot loader, you're essentially starting from nothing: a small chunk of code is loaded into memory, and executed. You can write the majority of your boot loader in C++, but you will need to bootstrap your own C++ runtime environment first. Assembly is really the only option for the first stage, as you need to set up a sensible environment for running anything higher-level. Doing enough to run C code is fairly straightforward -- you need: code and data loaded in the right place; there may be an additional part of the data area which must be zero-initialised; you need to point the stack pointer at a suitable area of memory for the stack. Then you can jump into the code at an appropriate point (e.g. main()) and expect that the basic language features will work. (It's possible that any features of the standard library that may have been implemented or linked in might require additional initialisation at this stage.) Getting a suitable environment going for C++ requires more effort, as it needs more initialisation here, and also has core language features which require runtime support (again, this is before considering library features). These include: running static constructors; memory allocation to support new and delete; support for run-time type information (RTTI); support for exceptions; probably some other things I've forgotten to mention. None of these are required until the C environment is up and running, so the code that handles these can be written in C rather than assembler (or even in a subset of C++ that does not make use of the above features). (The same principles apply in embedded systems, and it's not uncommon for such systems to make use of C++, but only in a limited way -- e.g. no exceptions and/or RTTI because the runtime support isn't implemented.)
3,273,455
3,273,485
c++ multithreaded task queue for scheduled tasks
I need to develop a module which will execute scheduled tasks. Each task is scheduled to be executed within X milliseconds. The module takes as a parameter an amount of worker threads to execute the tasks. The tasks are piled up in a queue which will probably be a priority queue, so a thread checks for the next-in-queue task (the one with the lowest "redemption" time), thus there's no need to iterate through all tasks each time. Is there any public library that does that or shall I roll my own? Note: I'm using VC2008 on Windows.
If you don't mind a Boost dependency, threadpool might fit your needs.
3,273,504
3,273,571
Is it possible to transform the types in a parameter pack?
Is it possible to transform the types of a parameter pack and pass it on? E.g. given the following: template<class... Args> struct X {}; template<class T> struct make_pointer { typedef T* type; }; template<class T> struct make_pointer<T*> { typedef T* type; }; Can we define a template magic or something similar so that the following assertion holds: typedef magic<X, make_pointer, int, char>::type A; typedef X<int*, char*> B; static_assert(is_same<A, B>::value, ":(");
Yes we can do that template<template<typename...> class List, template<typename> class Mod, typename ...Args> struct magic { typedef List<typename Mod<Args>::type...> type; };
3,273,621
3,274,702
C++ CppUnit Test (CPPUNIT_ASSERT)
I'm trying to do up a screen scraping assignment. My cpp works, but I don't know how to integrate my unit testing. I tried to do a bool check unit test for the file validity but it's giving me this error: error: cannot call member function 'bool ScreenScrape::getFile()' without object screenscrape.cpp: #include "screenscrape.h" using namespace std; int main() { ScreenScrape ss; int choice; ... ... ss.matchPatternTest(); } screenscrape.h: class ScreenScrape { public: ScreenScrape(); void parserTest(int choice); void matchPatternTest(); void setIndexValue(string data, string IndexName); void setIndexChange(string data); void setIndexPercent(string data); void setIndexDate(string data); bool getFile(); private: string IndexName; string IndexValue; string IndexChange; string IndexPercent; string IndexVID; string IndexCID; string IndexPID; string IndexDate; }; bool ScreenScrape::getFile() { string file1 = "yahoofinance.htm"; char* file2 = new char [file1.size()+1]; // parse file for c string conversion strcpy(file2, file1.c_str()); // converts to c string ifstream fin; fin.open(file2); if(fin.good()) return true; else return false; } screenscrapetest.cpp: #include "screenscrapetest.h" #include "screenscrape.h" CPPUNIT_TEST_SUITE_REGISTRATION (ScreenScrapeTest); void ScreenScrapeTest::fileTest() { CPPUNIT_ASSERT(ScreenScrape::getFile()); // test file validity } screenscrapetest.h: #ifndef _SCREENSCRAPETEST_H #define _SCREENSCRAPETEST_H #include <cppunit/TestCase.h> #include <cppunit/extensions/HelperMacros.h> #include "screenscrape.h" class ScreenScrapeTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE (ScreenScrapeTest); CPPUNIT_TEST (fileTest); CPPUNIT_TEST_SUITE_END (); public: void fileTest(); }; #endif I tried to declare "ScreenScrape ss;" under screenscrapetest.h, use an object (ss) to call getFile() but it's giving me multiples of this error: /home/user/NetBeansProjects/Assignment1/screenscrape.h:259: multiple definition of `ScreenScrape::getFile()' I only want to check for file validity with unit testing. Any help will be appreciated. Thanks in advance! Regards, Wallace
bool ScreenScrape::getFile() is not static, so cannot be called as a static function. You'll need to either (a) declare it as static or (b) create an instance of ScreenScrape and call getFile() from it. Looking at the code, it's not obvious why this function is a method of the class but perhaps it's still in the early stages of development. It can also be refactored to remove lots of redundant code: bool ScreenScrape::getFile() { std::ifstream fin("yahoofinance.htm"); return fin.good(); } Don't forget your include guards in screenscrape.h: #ifndef SCREENSCRAPE_H #define SCREENSCRAPE_H // Class declaration here... #endif//ndef SCREENSCRAPE_H And consider moving the implementation of getFile to the cpp source file. These two steps will prevent you getting the "multiple declaration" errors. This will fix your compilation errors, but checking for file validity is not a responsibility of a unit test. Unit tests should not interact with the filesystem.
3,273,654
3,276,231
ostream showbase does not show "0x" for zero value
PSPS: (a Pre-scripted Post-script) It has just come to mind that a more prescient question would have included the notion of: Is this non-display of "0x"(showbase) for zero-value integers a standard behaviour, or is it just a quirk of my MinGW implementation? It all began on a pleasant Sunday morning... I want to dump some Handles in their hex representation, and in a consistant, formatted way. I want a leading 0x and a fixed width, but this is proving to be elusive using the expected stream manipulators. The only way I've found to do this is to cast the Handles to an unsigned long. This seems a bit unreasonable, and I would expect that I'm not the only person to have ever wanted this.. Am I missing something in the standard hex manipulators? Is it because type void* (HANDLE) is simply defined outside of the normal hex-handling of ostream? In summary: I don't want to have to cast HANDLE to something which it isn't. and I don't want to hard code a "0x" prefix. Is there a way to do it using standard manipulators? or would I need to overload ostream's handling of HANDLE? (but that might overload me!) Here is my test code (and its output). I've used '.' as the fill char, for clarity, (I will actually be using '0') HANDLE h; ULONG ul; int iH = sizeof(h); // how many bytes to this void* type. int iW = iH*2; // the max number of hex digits (width). int iW2= iW+2; // the max number of hex digits (+ 2 for showbase "0x"). int iX = 4; // the number of bits per hex digit. int ib = iH*8; // the max number bits in HANDLE (exponent). int i; std::cout<<std::setfill('.'); // I actually want '0'; // the dot is for display clarity for( i=0; i<=ib; i+=iX ) { ul = (pow(2,i)-1); h = (HANDLE)ul; std::cout <<"// ul " <<std::setw(iW2)<<std::hex <<std::showbase <<std::internal <<ul <<" h " <<std::setw(iW2) /* hex,showbase,internal have no effect */ <<h <<" I want 0x"<<std::setw(iW) <<std::hex <<std::noshowbase<<std::right <<(ULONG)h <<std::endl; } // ul .........0 h .........0 I want 0x.......0 // ul 0x.......f h .......0xf I want 0x.......f // ul 0x......ff h ......0xff I want 0x......ff // ul 0x.....fff h .....0xfff I want 0x.....fff // ul 0x....ffff h ....0xffff I want 0x....ffff // ul 0x...fffff h ...0xfffff I want 0x...fffff // ul 0x..ffffff h ..0xffffff I want 0x..ffffff // ul 0x.fffffff h .0xfffffff I want 0x.fffffff // ul 0xffffffff h 0xffffffff I want 0xffffffff
I found this on https://bugzilla.redhat.com/show_bug.cgi?id=166735 - this is copy/paste straight from there. Doesn't sound like a bug to me. ISO C++98, 22.2.2.2.2/10 says std::showbase means prepending # printf conversion qualifier. 22.2.2.2.2/7 says std::hex means the printf conversion specifier is %x. So the behaviour is IMHO required to be the same as printf ("%#x", 0); But http://www.opengroup.org/onlinepubs/009695399/functions/fprintf.html says: "For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it." The same is in ISO C99, 7.19.6.1(6): "For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it." So it sounds like the C++98 standard (by saying 'make it like C's printf("%#x", 0)') requires this goofy behavior you're seeing. The only way to get what you want would be to get rid of the std::showbase and output 0x explicitly. Sorry.
3,273,729
3,323,769
Call C++ from an assembly bootloader
I have a small assembly bootloader that I got from this Tutorial. The code for the boot loader can be found here. I want to know if its possible to run c++ from this boot loader. I want to run a simple thing like this: #include <iostream> using namespace std; int main () { cout << "Hello World!\n"; return 0; } But as I can see it brings up 2 issues. First somehow the C++ file has to be included in the compiled bin file. Also #include <iostream>... Is iostream included included in a compiled C++ file or dose it need to be included in some sort of library in the boot loader? Thanks for any help as this is really puzzling me.
To call a C function from your assembly code, here's a schematic. Using g++ in place of gcc should allow you to use C++ code. But I wonder how much of 'C++' you'd be able to write since you cannot use the library functions, as some of the earlier replies to your question clearly point out. You may end up writing assembly in your C++ code finally! cboot.c void bootcode(void) { /* code */ } boot.asm # some where you have this line call bootcode # more code to follow You compile and link them this way to create the executable prog. nasm -f boot.o boot.asm gcc -c cboot.c gcc -o prog cboot.o boot.o
3,273,794
3,273,817
what's bubble sort good at?
Possible Duplicate: What is a bubble sort good for? I'am sure every algorithm has its advantage and disadvantage, so how about buble sort compared to other sorting algorithm? (ofcourse I hope the answer is other than "easy to learn")
It is easy to implement for linked lists, since you always swap adjacent nodes while traversing left to right repeatedly. Bubble sort is a stable sort.
3,273,993
3,274,025
how do I validate user input as a double in C++?
How would I check if the input is really a double? double x; while (1) { cout << '>'; if (cin >> x) { // valid number break; } else { // not a valid number cout << "Invalid Input! Please input a numerical value." << endl; } } //do other stuff... The above code infinitely outputs the Invalid Input! statement, so its not prompting for another input. I want to prompt for the input, check if it is legitimate... if its a double, go on... if it is NOT a double, prompt again. Any ideas?
Try this: while (1) { if (cin >> x) { // valid number break; } else { // not a valid number cout << "Invalid Input! Please input a numerical value." << endl; cin.clear(); while (cin.get() != '\n') ; // empty loop } } This basically clears the error state, then reads and discards everything that was entered on the previous line.
3,274,092
3,274,150
Creating a class with static pointers to explicitly loaded DLL functions
I want to have multiple instances of a DLLInterface class but as each object will have pointers to the same DLL functions I want these to be static. The below code doesn't compile. (I do have a reason for needing multiple instances containing the same pointers which the stripped down code below doesn't illustrate.) //Header file: typedef void (*DLLFunction)(); class DLLInterface { private: static HINSTANCE hinstDLL; public: static DLLFunction Do; DLLInterface() { if(!hinstDLL || !Do) { hinstDLL = LoadLibrary("DoubleThink.dll"); Do = (DLLFunction)GetProcAddress(hinstDLL, "Do"); } } }; I need to have all code contained within this header file also. (I know I can make it compile by adding statements like the following into a cpp file on the EXE but I need to avoid doing this. HINSTANCE DLLInterface::hinstDLL = 0; Thanks!
One trick I can think of is to use templates. The idea is you make the class the includes the static data a template class and then derive your actual class from it with some specific type: template <class T> class DLLInterfaceImpl; { private: static HINSTANCE hinstDLL; public: static DLLFunction Do; }; template <class T> HINSTANCE DllInterfaceImpl<T>::hInstDLL; template <class T> DLLFunction DllInterfaceImpl<T>::Do; class DllInterface : public DllInterfaceImpl<int> { }; Because DllInterfaceImpl is a template, you can put your static definitions in the header file and the compiler will do some "tricks" so that multiple definitions do not cause the link to fail.
3,274,441
3,274,567
Help Understanding these equations?
I asked a question regarding Bi linear transformations and received this answer: From that very page you posted, there's a link to the source code. I'll explain the bilinear transformation in http://www.antigrain.com/__code/include/agg_trans_bilinear.h.html The idea here is to find a transformation of the form: output_x = a * input_x + b * input_x * input_y + c * input_y + d output_y = e * input_x + f * input_x * input_y + g * input_y + h The term "bilinear" comes from each of those equations being linear in either of the input coordinates by themselves. We want to solve for the right values of a, b, c, and d. Say you have the reference rectangle r1, r2, r3, r4 which you want to map to (0,0), (1,0), (0,1), (1,1) (or some image coordinate system). For a,b,c,d: 0 = a * r1_x + b * r1_x * r1_y + c * r1_y + d 1 = a * r2_x + b * r2_x * r2_y + c * r2_y + d 0 = a * r3_x + b * r3_x * r3_y + c * r3_y + d 1 = a * r4_x + b * r4_x * r4_y + c * r4_y + d For e,f,g,h: 0 = e * r1_x + f * r1_x * r1_y + g * r1_y + h 0 = e * r2_x + f * r2_x * r2_y + g * r2_y + h 1 = e * r3_x + f * r3_x * r3_y + g * r3_y + h 1 = e * r4_x + f * r4_x * r4_y + g * r4_y + h You can solve this however you like best. (If you're familiar with matrix notation, these are two matrix equations for which the matrix is the same, and then you simply need to find the LU decomposition once, and solve the two unknown vectors). The coefficients are then applied to map the interior of the rectangle to the position in the rectangle. The problem is, I have input_x and input_y aswell as r1, r2, r3, r4, but I'm not sure how to achieve output_x and output_y. How do I solve such an equation? I'm only familiar with solving equations with 2 variables. Thanks
That's a terrible explanation you've found. Hopefully I can help you understand what's going on under the bonnet. What you want to do is map a rectangular area (one quadrilateral) into another (arbitrarily shaped) quadrilateral. Let's start with a simpler case: Linear interpolation (finding values that lie along a line) If you have a line from a to b, then you can find any point 'c' on that line by using this equation: c = ((1 - p) * a) + (p * b); This 'mixes' (interpolates) the values of the two positions along the straight line between them (linearly). If you use p=0 then the equation turns into c = (1 * a) + (0 * b) = a so at p=0 the equation gives you the point 'a'. When p=1, the equation becomes: c = (0 * a) + (1 * b) = b so at p=1, the equation gives you the point 'b'. At intermediate values of p, you get points on the line between a and b. (so at p=0.5 you get the point exactly half way between a and b) So, to copy the pixels from one line on the screen to another line on the screen, we can use linear interpolation to find the positions on the lines to read from and write to. for (float p = 0.0; p <= 1.0; p += 0.1) // copy 10 pixels from line 1 to line 2 DrawPixelOnLine2(p, GetPixelFromLine1(p)); These two methods would just use linear interpolation to calculate the correct positions to read and draw the pixels, like this: int ax = 0, ay = 100, bx = 50, by = 170; // line a-b goes from (0,100) to (50,170) int px = ((1-p) * ax) + (p * bx); // calc the x and y values separately int py = ((1-p) * ay) + (p * by); (Note that I have to use the calculation twice to do a 2D position. I could interpolate in 3D by simply adding the same calculation agaian for the az/bz/pz coordinates) So, now you can copy points from one arbitrary straight line to another. bi-linear interpolation is exactly the same, except we want to find a point within a rectangle rather than within a line, so we need two dimensions to describe where the point is in the rectangle (px along the bottom of the rectangle, and py up the side of the rectangle). Now you can locate any point in the rectangle with an (px,py) coordinate pair. To do the above mapping, we simply do the linear interpolation calculation in two dimensions: first we interpolate along the bottom and along the top to find two endpoints of a line that passes vertically through the middle of the rectangle. then we interpolate along this vertical line to find the final point in the middle of the rectangle. The "rectangle" doesn't need to be rectangular. The two dimensions can be used on any 4-sided shape (i.e. you can move the corners of your rectangle anywhere you like and the equations will still find the positions between the corners to fill in the area enclosed by the shape) In the example you have found, the author is using four points to describe the source shape (a,b,c,d) and another four points to describe the destination shape (e,f,g,h) In addition, they have made the calculations more efficient by solving the equations to populate a transformation matrix which can be multiplied against points to do the mapping process. However, the effect is the same as what I've described above. Hopefully my explanation makes it a bit easier for you to 'see' what the equations are doing.
3,274,445
3,277,168
Is object orientation bad for embedded systems, and why?
Many embedded engineers use c++, but some argue it's bad because it's "object oriented"? Is it true that being object oriented makes it bad for embedded systems, and if so, why is that really the case? Edit: Here's a quick reference for those who asked: so we prefer people not to use divide ..., malloc ..., or other object oriented practice that carry large penalty. I guess the question is are objects considered heavyweight in the context of an embedded system? Some of the answers here suggest they are and some suggest they're not.
Whilst I'm not sure it answers your question, I can summarise the reasons my previous companies source code was pure C. It's firstly worth summarising the situation: we wanted to write a large amount of "core" code that would be highly portable across a large number of ARM embedded systems (mostly mid-range mobile phones; both smart phones and ones running RTOSs of various ages) the platforms generally had a workable C compiler, though some for example didn't support floating point "double"s. in some cases the platform had a reasonable implementation of the standard library, but in many cases it didn't. a C++ compiler was not available on most platforms, and where it was available support for the C++ standard library, STL or exceptions was highly variable. debuggers often weren't available (a serial port you could send debug printfs to was considered a luxury) we always had access to a reasonable amount of memory, but often not to a reasonable malloc() implementation Given that, we worked entirely in C, and even then only a restricted set of C 89. The resulting code was highly portable. We often used object orientated concepts though. These days "embedded" is a very wide definition. It covers everything from 8 bit microprocessors with no RAM or C compilers upto what are essentially high end PCs (albeit not running Microsoft Windows) - I don't know where your project/company sits in that range.
3,274,463
3,294,965
Why does the chip control the language to choose
I've asked the question before what language should I learn for embedded development. Most embedded engineers said c and c++ are a must, but also pointed out that it depends on the chip. Can someone clarify? Is it a compiler issue or what? Do chips come with their own specific compilers (like a c compiler or c++ compiler) and that's why you have to use the language the compiler knows? Is it not possible to code and compile it elsewhere, then burn it to the chip directly in its compiled state? (I think I heard an acquaintance say something to this effect) I'm not sure how this works, as clearly I don't know much embedded systems or how they work. It's probably an easy answer for those of you who know.
It "depends on the chip" in three possible ways: Some very constrained architectures are not suited to C++, or at least C++ provides constructs not suited to such architectures so offers no benefit over C. Most 8 bit devices fall into this category, but by no means all; I have seen useful C++ code implemented on MegaAVR for example. Some devices are not supported by a C++ compiler. For example Microchip's dsPIC/PIC24 compiler is C only (third-party tools may have C++ support). The chip architecture is designed specifically for a particular language; for example INMOS Transputers invariably ran OCCAM. As well as C, C++, other possibilities are assembler, Forth, Ada, Pascal and many others, but C is almost ubiquitous; few chip vendors will release a new architecture or device without a C compiler being available from day-one. For other languages you will generally have to wait until a third-part decides to develop one, and that wait may be forever for a niche architecture. Is it not possible to code and compile it elsewhere, then burn it to the chip directly in its compiled state? That is called cross-compilation or cross-development, and is the usual development method for embedded systems. Most embedded systems lack the OS, file, performance and memory resources to self-host a compiler, and most developers want the comfort of a sophisticated development environment with IDEs, debuggers etc. in a familiar user-oriented desktop OS. I'm not sure how this works, as clearly I don't know much embedded systems or how they work. Get up-to-speed with some of these: http://www.state-machine.com/arm/Building_bare-metal_ARM_with_GNU.pdf http://www.eetimes.com/design/embedded http://www.amazon.com/exec/obidos/ASIN/020179523X http://www.amazon.com/Embedded-Systems-Firmware-Demystified-CD-ROM/dp/1578200997
3,274,582
3,274,610
What c++ features should be avoided for embedded development
I'm interested in compiling a list of c++ features that are not advisable for use in embedded systems (and which may cause people to recommend c over c++). Please try to add why if you know, or add your why to others' answers. Here's one for a start (the only one I know) Dynamic polymorphism, don't know why, but someone said it's "costly"
Certain features require run-time support, so if you miss the required support, you should avoid those features. In particular, the following features usually need extra run-time support: exceptions RTTI dynamic memory allocation virtual inheritance (a bit unsure about this one) People also usually mention templates, but they are only an advanced macro facility -- so you can freely use them in embedded systems. Still, you might want to avoid them since they can lead to code bloat after compilation. Your embedded system should come with documentation saying what, if any, run-time support for C++ (and otherwise) is available.
3,274,761
3,274,973
An example of an embedded project for a single person
I've been trying to wrap my head around embedded. Since I will be self-taught in this specific niche, I realize it will be harder to get a job in the field, so I'm hoping to add a completed project to my resume to prove to potential employers that I've done it and can do it again for them. Can someone suggest a project that I can undertake as a single person and actually be able to finish, but at the same time not too simple that it doesn't prove anything? Something reasonable that I can aim for. If you can substantiate your example with a project you worked on yourself, and mention how many people were involved, and how long it took to finish it, that would also help me gauge the difficulty of projects I see in general and rule out the ones that are probably too big for my capacity. It's very difficult to gauge the amount of work a project needs from my position.
Are you looking specifically at embedded software development, or are you interested in circuit board design as well? If it's just software, then I would suggest getting hold of an ARM development board (Possibly the Philips LPC range - sparkfun have some nice ones) that you can program via a bootloader over usb and start hacking. Get one with a display and an ethernet port and you can build up to making some sort of network attached sensor (temperature, water level, object counter, etc). Start out little (turn on a LED from a button) and work your way up. If you're also into the electronics side of things, I'd suggest something like an MP3 (or WAV) player and maybe stick to the AVR or PIC 8bit microcontrollers (AVR is used on the Arduino) as these are a little easier to deal with than ARM. Here you could start with a usb powered device that streams wav files from a PC serial port out to a pair of headphones, and build up to a battery powered board, feeding data to an MP3 decoder IC from an SD card. Some things you may want to learn & demonstrate: Understands the bounds of working with limited resources, including memory management (dynamic and/or static); resource management (locks, semaphores, mutex); multiple tasks (interrupts); and appropriate data structures Ability to interface with other devices/ICs over various interconnects (analog & digital IO, serial bus (RS232, I2C, SPI)) Ability to sanely structure a program and segment the various modules without producing 'spaghetti' code Ability to use source and integrate 3rd party libraries where appropriate (think FAT filesystem, or TCP/IP stack) Misc Tips: read and understand the datasheets (yes all of them) code and test on the desktop where possible, but understand that there are differences and bugs will still creep through (this is where it helps to be using a tool-chain that is common with the desktop - GCC is good, but the tools are generally CLI) use assert a lot - you can flash the line number of a failed assert using a single LED - this is invaluable Most of all have fun - it still makes me smile when you first get a new component working (display, motor, sensor). Embedded makes the world go round :)
3,274,781
3,275,394
Why can CImg achieve this kind of effect?
The compilation is done on the fly : only CImg functionalities really used by your program are compiled and appear in the compiled executable program. This leads to very compact code, without any unused stuffs. Any one knows the principle?
CImg is a header-only library, and they use templates liberally, which is what they're referring to. If they used a precompiled library of some kind (.dll/.lib/.a/.so) the library file would have to contain the entire CImg library, regardless of which bits of it you actually use. In the case of a statically linked library (.lib or .a), the linker can then strip out unused symbols, but that may depend on optimization settings. When the entire library is included in one or two headers, it is only actually compiled when you #include it, and so it is part of the same compilation process as the rest of your program, and the compiler can easily determine which parts of the library are used, and which ones aren't. And because the CImg API uses templates, no code is generated for functions that are never called. They are overselling it a bit though, because as the other answers point out, unused symbols will usually be stripped out anyway.
3,274,813
3,274,820
Rounding to nearest number in C++ using Boost?
Is there a way to round to the nearest number in the Boost library? I mean any number, 2's, 5's, 17's and so on and so forth. Or is there another way to do it?
int nearest = 5; int result = (input+nearest/2)/nearest*nearest;
3,274,836
3,274,851
Why should files be mounted in Linux
I got an old library which does some manipulation with files on floppy\ CD (transferring the files on network paths). This library has a thread which checks on each second whether the file (e.g. the floppy diskette\ the CD disk) is mounted. Why? What operations can be done only on mounted files? Thanks a lot.
To access a file in any way - read, write, execute, delete - you need to be able to specify its location. The location of a file is always its position in the directory tree, where Unix has just a single directory tree starting at a single root. Unless the device your file is on (and hence its own (sub)directory tree) is in the "main" directory tree, it isn't accessible. Incorporating a device's directory tree into the system's "main" directory tree is what's known in the Unix world as "mounting".
3,274,946
4,450,671
Sending parameters to a DLL to be boost::bind'ed
I have a DLL which has a function which accepts a function pointer converts it to a boost::function. This is then stored and then called from inside the DLL. I want to add a function to the DLL to handle member functions in a similar way. I know I need to use boost::bind to wrap the member function pointer and the object together. I want to do the binding on the DLL side though so the EXE does not require boost libraries to be included. How would you write this function? One which accepts a member function pointer and an object as arguments and binds them together. Thanks!
you're warned by @Kylotan, so you can try something like this: __declspec(dllexport) void store_mem_fn(void(Your_class::*mem_fn)(void), Your_class& instance) { std::vector<boost::function<void(void)> > container; container.push_back(boost::bind(mem_fn, instance)); }
3,275,031
3,275,050
Input terminal problems and map
I am using map to count the occurence of words. Here is the code. #include <iostream> #include <map> #include <string> using namespace std; int main() { map<string,int>wordcount; string s; while (cin>> s && s!="red") ++wordcount[s]; while (cin>>s && s!="red") cout << s << " " << wordcount[s] << endl; return 0; } I start the program, type words and at the last line enter the word "red", but it does not do anything. Then I type "red" the second time and it outputs: press any key to continue what is wrong?
Too groggy to write here, but I'll try a second time. :) If you write a lot of words, it will count them up until you write "red". The second loop will print the count for the words you input, but if you put "red" right away it will simply terminate the program without printing anything. Try running the program with the following input: one two two red zero one two red
3,275,252
3,275,260
Is there an equivalent to python's urllib in c/c++?
any c/c++ library out there that provides functions like getUrl, urlopen, post etc. ?
There are some libraries, libcurl and libwww amongst others. libcurl website even lists some other alternatives.
3,275,353
3,275,377
C aliasing rules and memcpy
While answering another question, I thought of the following example: void *p; unsigned x = 17; assert(sizeof(void*) >= sizeof(unsigned)); *(unsigned*)&p = 17; // (1) memcpy(&p, &x, sizeof(x)); // (2) Line 1 breaks aliasing rules. Line 2, however, is OK wrt. aliasing rules. The question is: why? Does the compiler have special built-in knowledge about functions such as memcpy, or are there some other rules that make memcpy OK? Is there a way of implementing memcpy-like functions in standard C without breaking the aliasing rules?
The C Standard is quite clear on it. The effective type of the object named by p is void*, because it has a declared type, see 6.5/6. The aliasing rules in C99 apply to reads and writes, and the write to void* through an unsigned lvalue in (1) is undefined behavior according to 6.5/7. In contrast, the memcpy of (2) is fine, because unsigned char* can alias any object (6.5/7). The Standard defines memcpy at 7.21.2/1 as For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value). The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined. However if there exist a use of p afterwards, that might cause undefined behavior depending on the bitpattern. If such a use does not happen, that code is fine in C. According to the C++ Standard, which in my opinion is far from clear on the issue, i think the following holds. Please don't take this interpretation as the only possible - the vague/incomplete specification leaves a lot of room for speculation. Line (1) is problematic because the alignment of &p might not be ok for the unsigned type. It changes the type of the object stored in p to be unsigned int. As long as you don't access that object later on through p, aliasing rules are not broken, but alignment requirements might still be. Line (2) however has no alignment problems, and is thus valid, as long as you don't access p afterwards as a void*, which might cause undefined behavior depending on how the void* type interprets the stored bitpattern. I don't think that the type of the object is changed thereby. There is a long GCC Bugreport that also discusses the implications of a write through a pointer that resulted from such a cast and what the difference to placement-new is (people on that list aren't agreeing what it is).
3,275,483
3,275,510
question about map sort
for example we have map map<char,int>mymap; mymap['a']=101; mymap['c']=45; mymap['b']=76; mymap['d']=98; i know that if we iterate through map it will print element according to following way a>=101; b>=76; c>=45; d>=98; how do such that small keys refer small values? or a-45 b-76 c-98 d-101 ? thanks
If I'm understanding you correctly, you do not want to permanently associate values at all, you're wanting to order two different sets of values, and then line them up together at some point. In which case, do not use a std::map. You want two different std::set (or multiset if you want to allow duplicate values) which orders the values separately. Then iterate through the two together at some point.
3,275,601
3,275,700
Architectural C++/STL question about iterator usage for O(1) list removal by external systems
This is a pretty straightforward architectural question, however it's been niggling at me for ages. The whole point of using a list, for me anyway, is that it's O(1) insert/remove. The only way to have an O(1) removal is to have an iterator for erase(). The only way to get an iterator is to keep hold of it from the initial insert() or to find it by iteration. So, what to pass around; an Iterator or a pointer? It would seem that if it's important to have fast removal, such as some sort of large list which is changing very frequently, you should pass around an iterator, and if you're not worried about the time to find the item in the list, then pass around the pointer. Here is a typical cut-down example: In this example we have some type called Foo. Foo is likely to be a base class pointer, but it's not here for simplicity. Then we have FooManger, which holds a list of shared_ptr, FooPtr . The manager is responsible for the lifetime of the object once it's been passed to it. Now, what to return from addFoo()? If I return a FooPtr then I can never remove it from the list in O(1), because I will have to find it in the list. If I return a std::list::iterator, FooPtrListIterator, then anywhere I need to remove the FooPtr I can, just by dereferencing the iterator. In this example I have a contrived example of a Foo which can kill itself under some circumstance, Foo::killWhenConditionMet(). Imagine some Foo that has a timer which is ticking down to 0, at which point it needs to ask the manager to delete itself. The trouble is that 'this' is a naked Foo*, so the only way to delete itself, is to call FooManager::eraseFoo() with a raw pointer. Now the manager has to search for the object pointer to get an iterator so it can be erased from the list, and destroyed. The only way around that is to store the iterator in the object. i.e Foo has a FooPtrListIterator as a member variable. struct Foo; typedef boost::shared_ptr<Foo> FooPtr; typedef std::list<FooPtr> FooPtrList; typedef FooPtrList::iterator FooPtrListIterator; struct FooManager { FooPtrList l; FooPtrListIterator addFoo(Foo *foo) { return l.insert(l.begin(), FooPtr(foo)); } void eraseFoo(FooPtrListIterator foo) { l.erase(foo); } void eraseFoo(Foo *foo) { for (FooPtrListIterator it=l.begin(), ite=l.end(); it!=ite; ++it) { if ((*it).get()==foo){ eraseFoo(it); return; } } assert("foo not found!"); } }; FooManager g_fm; struct Foo { int _v; Foo(int v):_v(v) { } ~Foo() { printf("~Foo %d\n", _v); } void print() { printf("%d\n", _v); } void killWhenConditionMet() { // Do something that will eventually kill this object, like a timer g_fm.eraseFoo(this); } }; void printList(FooPtrList &l) { printf("-\n"); for (FooPtrListIterator it=l.begin(), ite=l.end(); it!=ite; ++it) { (*it)->print(); } } void test2() { FooPtrListIterator it1=g_fm.addFoo(new Foo(1)); printList(g_fm.l); FooPtrListIterator it2=g_fm.addFoo(new Foo(2)); printList(g_fm.l); FooPtrListIterator it3=g_fm.addFoo(new Foo(3)); printList(g_fm.l); (*it2)->killWhenConditionMet(); printList(g_fm.l); } So, the questions I have are: 1. If an object needs to delete itself, or have some other system delete it, in O(1), do I have to store an iterator to object, inside the object? If so, are there any gotchas to do with iterators becoming invalid due other container iterations? Is there simply another way to do this? As a side question, does anyone know why and of the 'push*' stl container operations don't return the resultant iterator, meaning one has to resort to 'insert*'. Please, no answers that say "don't pre-optimise", it drives me nuts. ;) This is an architectural question.
The one problem I see with storing the iterator in the object is that you must be careful of deleting the object from some other iterator, as your objects destructor does not know where it was destroyed from, so you can end up with an invalid iterator in the destructor. The reason that push* does not return an iterator is that it is the inverse of pop*, allowing you to treat your container as a stack, queue, or deque.
3,275,612
3,275,632
What is the explicit keyword for in c++?
Possible Duplicate: What does the explicit keyword in C++ mean? explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(filename); } what's the difference with or without it?
It's use to decorate constructors; a constructor so decorated cannot be used by the compiler for implicit conversions. C++ allows up to one user-provided conversion, where "user-provided" means, "by means of a class constructor", e.g., in : class circle { circle( const int r ) ; } circle c = 3 ; // implicit conversion using ctor the compiler will call the circle ctor here, constructinmg circle c with a value of 3 for r. explicit is used when you don't want this. Adding explicit means that you'd have to explicitly construct: class circle { explicit circle( const int r ) ; } // circle c = 3 ; implicit conversion not available now circle c(3); // explicit and allowed
3,275,793
3,278,004
Are there specialities within the embedded fields
I've started learning embedded and its 2 main languages (c and c++). But I'm starting to realize that despite the simple learning requirements, embedded is a whole world in and of itself. And once you deal with real projects, you start to realize that you need to learn more "stuff" specific to the hardware used in the device you're working on. This is an issue that rarely came up with the software-only projects I currently work on. Is it possible to fragment this field into sub-fields? I'm thinking that those with experience in the field may have noticed that some types of projects are different from other types, which has led them to maybe maybe come up with their own categories. For example, when you run into a project, you may think to yourself that it's "outside your field"? Does that happen to you? and if so, what would you call your sub-field or what other sub-fields have you encountered?
Here are a few sub-specialities I can think of: Assembly Language Specialist Yep. You need to know C and C++. But some people also specialize in assembly. These are the experts that are called up to port a RTOS to a new chip, or to squeeze every drop of performance from a highly constrained embedded system (usually to save $$ per unit). This person probably is not needed that much these days... but.. yet still critical from time to time. Device Driver Specialist comfortable living between a real OS or RTOS and a piece of hardware. This person is usually comfortable with lab tools like o-scopes or logic analyzers, thinking in "hex", and understanding the critical nature of timing with HW. This person reads device data sheets for fun at night, and gets excited about creating the perfect porting driver for some new device. DSP Specialist Digital Signal Processing seems to be its own sub-specialty of embedded, although perhaps a software engineer may not know the exact algorithm details, and may only be implementing what a system or electrical engineer requires. However, understanding sampling rate theory, FFTs, and some foundational elements from "DSP" is handy and maybe required. And you still generally must be very aware of timing and your target hardware's restrictions ( sampling rate, noise, bits per sample, etc). Control Theory Specialist Perhaps the same issue as with DSP: a system or electrical engineer may provide the detailed specs. But, then again, familiarity with various motors, sensors, and other controllers handled by a microcontroller, would be great. Throw in a Bode plot, some Laplace transforms or two and some higher math skills... that couldn't hurt too much! Networking Specialist basically the same as the PC world "networking". Many embedded devices are adding networking connectivity features these days. TCP/IP sockets, http, etc good to know and understand how to use in a resource constrained device. Throw in USB and Bluetooth for good measure. UI Specialist more and more embedded devices include 2D graphics, and now more include 3D graphics thanks to the influence of iPhones, etc. Even though these are still "fat" systems by other embedded device standards, they are still limited. Just read a bit in the Android Development Guide, and you will realize that you still must consider responsiveness, performance, etc, even in a high end cell phone. http://developer.android.com/guide/practices/design/performance.html And then, of course, every industry is a specialization unto itself. Consumer Electronics, Military, Avionics, Robotics, Industrial Machines, Medical Devices, etc... Have fun and good luck!
3,275,821
3,275,831
Anyone knows what `cimg::exception_mode() = 0;` does?
const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; Never see this kinda syntax before.
exception mode might be returning a reference, and it is being set to 0. For example: unsigned int& exception_mode() { return mode; }; So, the second line would be equivalent to: void set_exception_mode( uint v ) { mode = v; }; BTW, it is really ugly! I would avoid this kinda syntax as much as I could.
3,275,904
3,275,954
Why can the code between ifndef/endif still get run here?
#define cimg_use_jpeg 2 #ifndef cimg_use_jpeg //code goes here #endif I really don't understand...
Every time things similar to this (so-called impossible things) happen me, the reason is: The code I see in my editor is not the code that runs. This can happen in many ways. forgetting to make forgetting to save saving a copy of the code running in a different evironment from the one you compiled to the new code ran but I opened and am looking at the old output
3,275,983
3,276,019
QT: Is it a good idea to base my domain objects on QObject?
I'm reasonably new to using the QT framework in combination with C++. I was wondering: Is it a good idea to base my domain classes on QObject? Or should I only do this for classes higher up in the hierarchy? (closer to the user interface level). The QT documentation isn't clear on this: Taken from the QT documentation: The meta-object system is a C++ extension that makes the language better suited to true component GUI programming. Obviously I want to build my application in a nice well structured way. Over the past few days I have been browsing through the QT documentation in order to find an answer to this question. I don't want to make some elementary mistake which will make my application limp for all eternity ;-). I have already looked at the basic documentation for QObject and the Qt Object model. I also found a freshmeat article which helped but didn't really help me reach a conclusion. Something else that confuses me is that QT itself doesn't seem to be consistent on this matter because not all QT classes use QObject as a base class. The advantages of using QObject as a base class as I see them: Hierarchy Signals and slots Properties Being able to use guarded pointers Internationalization However, I don't require any of these functionalities in most of my domain classes. Is there a best practise rule for this? Or should the rule be: use it if you require any of the points mentioned above? Hope I didn't make this too confusing :-)
In general, unless there is a "compelling need," you are better off keeping your domain classes "vanilla." That gives you the most flexibility in the future (e.g. re-using them in a non-Qt environment).
3,276,001
3,276,056
STL erase-remove idiom vs custom delete operation and valgrind
This is an attempt to rewrite some old homework using STL algorithms instead of hand-written loops and whatnot. I have a class called Database which holds a Vector<Media *>, where Media * can be (among other things) a CD, or a Book. Database is the only class that handles dynamic memory, and when the program starts it reads a file formatted as seen below (somewhat simplified), allocating space as it reads the entries, adding them to the vector (v_) above. CD Artist Album Idnumber Book Author Title Idnumber Book ... ... Deleting these object works as expected when using a hand-written loop: EDIT: Sorry I spoke too soon, it's not actually a 'hand-written' loop per-se.. I've been editing the project to remove hand-written loops and this actually uses the find_if algorithm and a manual deletion, but the question is till valid. /EDIT. typedef vector<Media *>::iterator v_iter; ... void Database::removeById(int id) { v_iter it = find_if(v_.begin(), v_.end(), Comparer(id)); if (it != v_.end()) { delete *it; v_.erase(it); } } That should be pretty self-explanatory - the functor returns true if it find an id matching the parameter, and the object is destroyed. This works and valgrind reports no memory leaks, but since I'd like to use the STL, the obvious solution should be to use the erase-remove idiom, resulting in something like below void Database::removeById(int id) { v_.erase(remove_if(v_.begin(), v_.end(), Comparer(id)), v_.end()); }; This, however, 'works' but causes a memory leak according to valgrind, so what gives? The first version works fine with no leaks at all - while this one always show 3 allocs 'not freed' for every Media object I delete.
This is why you should always, ALWAYS use smart pointers. The reason that you have a problem is because you used a dumb pointer, removed it from the vector, but that didn't trigger freeing the memory it pointed to. Instead, you should use a smart pointer that will always free the pointed-to memory, where removal from the vector is equal to freeing the pointed-to memory.
3,276,235
3,379,328
relation between access specifiers and using initializer lists for POD types in c++0x
take two following classes: class Test1{ public: Test1()=default; Test1(char in1,char in2):char1(in1),char2(in2){} char char1; char char2; }; class Test2{ public: Test2()=default; Test2(char in1,char in2):char1(in1),char2(in2){} private: char char1; char char2; }; I know in c++0x both of these classes are considered as POD types and we can initialize objects of them using initializer lists as below: Test1 obj1={'a','b'};//valid in c++0x Test2 obj2={'a','b'};//valid in c++0x But I wonder what the technical reason is that when we have different access specifiers in a class like below, it's not possible to use initializer list for initializing objects of that class and that class is not considered as a POD type ? class Test{ public: Test()=default; Test(char in1,char in2):char1(in1),char2(in2){} char char1; private: char char2; }; Test obj={'a','b'};//invalid in c++0x In case you don't know definition of PODs in c++0x: A class/struct is considered a POD if it is trivial, standard-layout, and if all of its non-static members are PODs. A trivial class or struct is defined as one that: Has a trivial default constructor. This may use the default constructor syntax (SomeConstructor() = default;). Has a trivial copy constructor, which may use the default syntax. Has a trivial copy assignment operator, which may use the default syntax. Has a trivial destructor, which must not be virtual. A standard-layout class or struct is defined as one that: Has only non-static data members that are of standard-layout type Has the same access control (public, private, protected) for all non-static members Has no virtual functions Has no virtual base classes Has only base classes that are of standard-layout type Has no base classes of the same type as the first defined non-static member Either has no base classes with non-static members, or has no non-static data members in the most derived class and at most one base class with non-static members. In essence, there may be only one class in this class's hierarchy that has non-static members. In case you don't know what a trivial constructor or operator is: Compiler generates a trivial one of each of following items for a class, in case it isn't user-declared: Copy constructor, destructor and copy assignment operator. And also if there's no user-declared constructor for a class, a trivial default constructor is generated for that class, in case there are any user-declared constructors you can use the syntax(SomeConstructor() = default;) to make your own trivial default constructor.
class Test{ public: Test()=default; Test(char in1,char in2):char1(in1),char2(in2){} char char1; private: char char2; }; considering above class following syntax is valid in c++0x: Test obj={'a','b'};//valid in c++0x The final proposal is here.
3,276,284
3,276,343
I'm doing funky things with placement new, and things are failing. Workarounds?
I have a very large, spread out class that is essentially a very contrived two dimensional linked list. I want to be able to "compile" it, by which I mean I want to finalize the list, so that only read accesses may be made, and then move all the elements into contiguous memory spaces. My rough solution is this: #include <new> ... MyListNode* pool = new MyListNode[length]; new(&pool[position]) MyListNode(); The trouble is that I essentially have two classes, one allocated with new and the other allocated with this method up here, and when I try to delete any of the objects allocated by the above method, glibc kills the program because of an invalid pointer. The natural solution is to create two classes, and just use runtime polymorphism to provide one interface but two implementation, etc. Is there any way that the memory standard in C++ permits this kind of jiggery pokery?
Are you calling delete on one of the objects in your array? Or are you manually invoking the destructor to mirror the placement new? Since you have one call to non-placement new, you should only have one call to delete. And since you have n-calls to placement-new, you should manually invoke the destructor n times. So, you may want something like this: // Allocate an array of chars instead of an array of MyListNode. Since we // are going to use placement new, this is necessary if MyListNode has a // a default constructor MyListNode* pool = static_cast<MyListNode *>(new char[sizeof(MyListNode) * length); for (size_t position = 0; position < length; ++position) new(&pool[position]) MyListNode(); ... for (position = 0; position < length; ++position) pool[position].~MyListNode() delete[] static_cast<char *>(pool);
3,276,341
3,276,362
Solving a system of equations programmably?
Possible Duplicate: System of linear equations in C++? I have the following 2 systems of equations: For a,b,c,d: 0 = a * r1_x + b * r1_x * r1_y + c * r1_y + d 1 = a * r2_x + b * r2_x * r2_y + c * r2_y + d 0 = a * r3_x + b * r3_x * r3_y + c * r3_y + d 1 = a * r4_x + b * r4_x * r4_y + c * r4_y + d For e,f,g,h: 0 = e * r1_x + f * r1_x * r1_y + g * r1_y + h 0 = e * r2_x + f * r2_x * r2_y + g * r2_y + h 1 = e * r3_x + f * r3_x * r3_y + g * r3_y + h 1 = e * r4_x + f * r4_x * r4_y + g * r4_y + h I know the values of r1_x, r1_y, r2_x, r2_y, r3_x, r3_y, r4_x, r4_y, and need to solve for a,b,c,d in the first one, and ,e,f,g, h in the second. I know how I would solve these with pencil and paper, but I'm really unsure how to program it. How could I solve the above equations in C or C++ (or psuedocode). Thanks
You can map it to a matrix system, A x = b, where A is the coefficient matrix, b is the solution vector, and x are the unknowns. You can either implement Gaussian elimination, or use a well known library. If you use LAPACK, the routine you want it dgesv.
3,276,372
3,276,389
Freeing dynamically allocated memory
In C++, when you make a new variable on the heap like this: int* a = new int; you can tell C++ to reclaim the memory by using delete like this: delete a; However, when your program closes, does it automatically free the memory that was allocated with new?
Yes, it is automatically reclaimed, but if you intend to write a huge program that makes use of the heap extensively and not call delete anywhere, you are bound to run out of heap memory quickly, which will crash your program. Therefore, it is a must to carefully manage your memory and free dynamically allocated data with a matching delete for every new (or delete [] if using new []), as soon as you no longer require the said variable.
3,276,390
3,283,069
OpenGL Hemisphere Texture Mapping
I need to have a hemisphere in opengl. I found a drawSphere function which I modified to draw half the lats (which ends up drawing half of the sphere) which is what I wanted. It does this correctly. However, I don't know what i should do with glTexCoordf to get the textures to map properly onto this half sphere. I'm really not great with opengl, and I've tried countless variations but I just can't get the textures to appear properly on it. void drawHemisphere(double r, int lats, int longs) { int i, j; int halfLats = lats / 2; for(i = 0; i <= halfLats; i++) { double lat0 = M_PI * (-0.5 + (double) (i - 1) / lats); double z0 = sin(lat0); double zr0 = cos(lat0); double lat1 = M_PI * (-0.5 + (double) i / lats); double z1 = sin(lat1); double zr1 = cos(lat1); glBegin(GL_QUAD_STRIP); for(j = 0; j <= longs; j++) { double lng = 2 * M_PI * (double) (j - 1) / longs; double x = cos(lng); double y = sin(lng); // glTexCoordf() glNormal3f(x * zr0, y * zr0, z0); glVertex3f(x * zr0, y * zr0, z0); // glTexCoordf() glNormal3f(x * zr1, y * zr1, z1); glVertex3f(x * zr1, y * zr1, z1); } glEnd(); } } Does anyone have any idea of what values I should be putting in? Or what I need to calculate for it? Thanks!
Basically, you shouldn't need anything fancy there. The texture coordinate space ranges from zero to one. So pick some intermediate values for the vertices in between. I can't explain it more thoroughly without image, so the best I can do is to point You to this article: UV mapping, it's a good starting point. Hope this helps as a starter. Here's my guess: { double lng = 2 * M_PI * (double) (j - 1) / longs; double x = cos(lng); double y = sin(lng); double s1, s2, t; s1 = ((double) i) / halfLats; s2 = ((double) i + 1) / halfLats; t = ((double) j) / longs; glTexCoord2d(s1, t); glNormal3d(x * zr0, y * zr0, z0); glVertex3d(x * zr0, y * zr0, z0); glTexCoord2d(s2, t); glNormal3d(x * zr1, y * zr1, z1); glVertex3d(x * zr1, y * zr1, z1); } Remember to properly set texture in OpenGL. An example call with texture: glActiveTexture(GL_TEXTURE0); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); // texture must be bound & enabled texture.bind(); texture.enable(); drawHemisphere(1, 40, 40); texture.disable(); I used Java + JOGL to test it, so it's not one-to-one C++ solution, but conceptually it should be the same. At least You have proper glTexCoord2d() calls.
3,276,479
3,435,210
Using member of template class to instantiate template default parameter in MSVC++
The following piece of code is a reduced sample from the large project I'm trying to port from GCC/G++ to Microsoft Visual C++ 2010. It compiles fine with G++, but with MSVC++, it throws errors, and I'm having trouble understanding why. template <typename A, typename B = typename A::C::D> // line 1 struct foo { typedef int type; }; template <template <typename> class E, typename T> typename foo<E<T> >::type // line 8 bar(){} The error messages from MSVC++ are: example1.cpp(1) : error C2027: use of undefined type 'E<T>' example1.cpp(8) : error C2146: syntax error : missing ',' before identifier 'D' example1.cpp(8) : error C2065: 'D' : undeclared identifier I've tried a few changes to narrow down the problem a bit, and while I don't fully understand it, here's what I've discovered: If in line 1 I replace A::C::D with A::C, it works fine. If I replace template <typename> class E with just typename E and make that foo<E>, it works fine. If explicitly specify the second template argument to foo in line 8, like so, it works fine: typename foo<E<T>, typename E<T>::C::D>::type // line 8 And, if I replace the use of A::C::D with something innocuous like typename B = A in line 1, but add a different use of A::C::D as typedef typename A::C::D qux; to the definition of foo, that also works fine. Any ideas? What bit of C++ rules am I missing?
I reported this as a bug with Microsoft as per jpalecek's suggestion, and Microsoft has confirmed that it is indeed a fault in their compiler: https://connect.microsoft.com/VisualStudio/feedback/details/576196
3,276,486
3,276,548
question about templates
i have following code #include <iostream> #include <utility> using namespace std; namespace rel_ops{ template<class t>bool operator!=(const t& x, const t& y){ return !(x==y);} template <class t>bool operator>(const t& x,const t& y){ return y<x;} template <class t>bool operator <=(const t& x,const t& y){ return !(y<x);} template <class t> bool operator>=(const t& x,t& y) { return ! (x<y);} } int main(){ int x,y; cin>>x>>y; return 0; } i have question how implement it in main function? how implements its operators in main function
You just need to add: using namespace rel_ops; Note that rel_ops is already defined in std. You do not need to redefine this namespace and its contents in your code. To use the definition already present in std, you use just: #include <utility> using namespace std::rel_ops;
3,276,576
3,276,584
C++/STL: XOR of two set
Given two STL sets, I want to find out the XOR of them. Is there an easy, pre-existing way to do that?
You can use std::set_symmetric_difference from the C++ standard library.
3,276,589
3,276,615
question about class
Possible Duplicates: Why should I prefer to use member initialization list? C++ - what does the colon after a constructor mean? here is following code class vector2d { public: double x,y; vector2d (double px,double py): x(px), y(py) {} i dont understand this line vector2d (double px,double py): x(px), y(py) {} is it same as vector2d(double px,double py){ x=px;y=py;}? or?
Yes, it's the same in your example. However, there's a subtle difference: x(px) initializes x to px, but x=px assigns it. You'll not know the difference for a doublevariable, but if x where a class there would be a big difference. Let's pretend that x is a class of type foo: x(px) would call the foo copy constructor, foo::foo(foo &classToCopyFrom). x=px on the other hand, would first call the foo default constructor, then it would call the foo assignment operator. This is a good reason that you should prefer x(px) in most cases.
3,276,596
3,277,100
Dependent Non-Type Template Parameters
Consider the following class: class Foo { enum Flags {Bar, Baz, Bax}; template<Flags, class = void> struct Internal; template<class unused> struct Internal<Bar, unused> {/* ... */}; template<class unused> struct Internal<Baz, unused> {/* ... */}; template<class unused> struct Internal<Bax, unused> {/* ... */}; }; The class outline above compiles and functions as expected when tested on VC++ 2010 and Comeau C++. However, when Foo is made into a template itself, the above snippet breaks under VC++ 2010. For example, the following snippet: template<class> class Foo { // Same contents as the original non-templated Foo. }; Yields the following error class: C2754: 'Foo<<unnamed-symbol>>::Internal<Bar,unused>' : a partial specialization cannot have a dependent non-type template parameter C2754: 'Foo<<unnamed-symbol>>::Internal<Baz,unused>' : a partial specialization cannot have a dependent non-type template parameter C2754: 'Foo<<unnamed-symbol>>::Internal<Bax,unused>' : a partial specialization cannot have a dependent non-type template parameter Can someone explain what is going on here in plain English? How can I fix this (i.e., keep internal pseudo-explicit specializations in a templated Foo) on VC++ 2010?
How can I fix this (i.e., keep internal pseudo-explicit specializations in a templated Foo) on VC++ 2010? You can make the enumeration type non-dependent by declaring it in a non-template base class (C++03 made nested classes dependent in #108 but that doesn't include enumeration, but even if, such code would still be legal). struct FooBase { enum Flags {Bar, Baz, Bax}; }; template<class> class Foo : public FooBase { template< ::FooBase::Flags, class = void > struct Internal; // same other stuff ... }; The "error class" link already gives a description of the intended cases where the error should be risen. The error thinks that all dependent types are forbidden, but in fact this is what the Standard says: The type of a template parameter corresponding to a specialized non-type argument shall not be dependent on a parameter of the specialization. So even if the name Flags would be somehow dependent, that wouldn't make it ill-formed as long as it doesn't depend on a parameter of the specialization like in the example of your "error class" link.
3,276,778
3,276,815
Mapping class to instance
I'm trying to build a simple entity/component system in c++ base on the second answer to this question : Best way to organize entities in a game? Now, I would like to have a static std::map that returns (and even automatically create, if possible). What I am thinking is something along the lines of: PositionComponent *pos = systems[PositionComponent].instances[myEntityID]; What would be the best way to achieve that?
Maybe this? std::map< std::type_info*, Something > systems; Then you can do: Something sth = systems[ &typeid(PositionComponent) ]; Just out of curiosity, I checked the assembler code of this C++ code #include <typeinfo> #include <cstdio> class Foo { virtual ~Foo() {} }; int main() { printf("%p\n", &typeid(Foo)); } to be sure that it is really a constant. Assembler (stripped) outputted by GCC (without any optimisations): .globl _main _main: LFB27: pushl %ebp LCFI0: movl %esp, %ebp LCFI1: pushl %ebx LCFI2: subl $20, %esp LCFI3: call L3 "L00000000001$pb": L3: popl %ebx leal L__ZTI3Foo$non_lazy_ptr-"L00000000001$pb"(%ebx), %eax movl (%eax), %eax movl %eax, 4(%esp) leal LC0-"L00000000001$pb"(%ebx), %eax movl %eax, (%esp) call _printf movl $0, %eax addl $20, %esp popl %ebx leave ret So it actually has to read the L__ZTI3Foo$non_lazy_ptr symbol (I wonder though that this is not constant -- maybe with other compiler options or with other compilers, it is). So a constant may be slightly faster (if the compiler sees the constant at compile time) because you save a read.
3,276,835
3,276,886
Declaring two variable in a conditional?
Can I declare two variables in a conditional in C++. The compiler gave an error but still I think I should get an opinion: int main() { double d1 = 0; if((double d2 = d1) || (double d3 = 10)) cout << "wow" << endl; return 0; }
You can only do that for one variable if(double d2 = d1) cout << "wow" << endl; else if(double d3 = 10) cout << "wow" << endl; But i would declare them outside of the conditions. If you are scared about the scope, you can always limit it: { double d2 = d1; double d3 = 10; if(d2 || d3) cout << "wow" << endl; } Of course, this evaluates the second initializer even if d2 evaluates to true. But i assume that's not important.
3,276,906
3,276,964
istream_iterator leaking memory
All right, you guys were very helpful with my last question, so I'll try another one. This is also homework and while the last one was quite old, this has been submitted and is waiting to be marked. So if there's anything that will bite me it'll probably be this problem. I've obfuscated the class names and such since it's still possible to submit the assignment (for other students). I have a class whose only member is a pointer to an Object. This class is constructed to expose certain operations from the pointer it is currently holding - the Object *o_ which is a base class to Object{1, 2, 3, ...}. Now, I'm able to do the following without any memory leaks or crashes. std::vector<ObjectPtr> v; v.push_back(ObjectPtr(new Object1(..., ..., ...))); v.push_back(ObjectPtr(new Object2(..., ...))); v.push_back(ObjectPtr(new Object1(.., .., ..))); // Copy Constructor Ptr std::vector<ObjectPtr> v2(v); // Assignment Operator Ptr std::vector<ObjectPtr> v3; v3 = v2; All this works, and there are no memory leaks. But if I try to read in the contents from a file with a istream_iterator<ObjectPtr> it starts to leak. ObjectPtr is the only class handling dynamic memory and the Object *o_ is either set to NULL or allocated by Object{1, 2, 3, ...}. The file to be read looks like this Object1 ... ... Object2 ... ... Object1 .. std::ifstream is("file.txt"); std::istream_iterator<ObjectPtr> in(is), end; for (; in != end; ++in) cout << *in << "\n"; The friend function in ObjectPtr used to read in these values looks like friend istream &operator>>(istream &is, ObjectPtr &op) { std::string tmp; while (std::getline(is, tmp)) { if (tmp == "Object1") { op.o_ = new Object1; return is >> (Object1 &)*(op.o_); // Send it to operator>> for Object1 } if (tmp == "Object2") { op.o_ = new Object2; return is >> (Object2 &)*(op.o_); } ... } return is; } Somewhere here it starts unicorning on me, and I'd really like to know why. In a nutshell - istream_iterator leaks memory while assignment and copy constructor works properly, which leads me to believe that the classes Object{1, 2, 3, 4, ..} are constructed correctly, and the problem is to be found within operator>>.
Here's the first thing occurring to me. I don't know whether that's the issue you're hunting for: friend istream &operator>>(istream &is, ObjectPtr &op) { std::string tmp; while (std::getline(is, tmp)) { if (tmp == "Object1") { op.o_ = new Object1; In that last line, what happens to the old value in op.o? Remember, streaming into an object means to stream into a fully constructed object and you have to mind the object's old data. (That's why often prefer constructors taking std::istream. For complex objects that safes the initialization for an object that is to be changed in the very next moment.) Does ObjectPtr have an assignment operator or a swap() member function? If so, it might be easier to implement the input operator by constructing a new object and assign it to/swap it with op.
3,276,951
3,276,970
Diamond sub-problem: non-multiple inheritance in side branch still require class constructor
Strange problem occurred when I tried to "solve" usual diamond problem in a usual way - using virtual inheritance: A / \* both virtual B C \ / D However my base class A doesn't have default constructor, so I was to call it manually from D. However when I try to add a class E into this diamond as C-inherited A / \* both virtual B C \ / \ D E it is still needed to call constructor of A in E constructor manually, i.e. C doesn't what to create A from E even though there is neither multiple inheritance nor diamond A-C-E. class A {public: A (int _N): N(_N) {}; void show() {cout<<"A"<<N;} protected: int N; }; class B: public virtual A { public: B(int n): A(2*n) {}; void show() { cout<<"B"<<N;} }; class C: public virtual A { public: C(int n): A(3*n) {}; void show() { cout<<"C"<<N;} }; class D: public B,C { public: D(): B(1), C(2), A(3) {}; void show() { cout<<"D"<<N;} }; class E: public virtual C { public: E(): C(1) {}; void show() { cout<<"E"<<N;} }; int main() {D d; // OK A *a = &d; a->show(); E e; // NOT OK, no function A::A() to call in E::E() A *a2 = &e; a2->show(); return 0; } Is it possible to solve this issue without calling constructor of A from E? I need C to do it properly :-). Or is it possible not to try to solve diamond problem at all: A A | | no virtual at all B C \ / \ D E and still try to declare object of class D with two instances of A but telling compiler to use A of C when colling from D each time? When I try to add using C::A into the declaration of D it still produce error of unambiguous base A.
Is it possible to solve this issue without calling constructor of A from E? I need C to do it properly :-). The constructor for the most derived class (in this case, E) is responsible for calling the constructor for any virtual base classes. The constructor of C cannot call the constructor of A because C is not the most derived class. Virtual base classes are initialized before any direct base classes, so E must initialize by A before it can initialize C.
3,276,971
3,284,154
Xerces-C++ DOM node line/column number location
I'm writing a custom XML validator using Xerces-C++. My current approach loads the document into a DOM, and then checks are performed on it. What I need is a way to access the line/column number of a node in the DOM. I've been reading the API docs and googling, but I'm coming up short. Is it possible to somehow retrieve this kind of information about the nodes? Implementing the XMLValidator interface looks like it would probably provide me with that kind of info, but it would require completely rewriting the intended validation architecture. Frankly, an XMLValidator approach seems ugly and monolithic. I have a different and much simpler validation system in mind (one that is also easily parallelizable) and everything works; all I need is the line/column number info of the nodes. The Qt DOM implementation that I've used before (and which I can't use now) provides this information up front, so I can't see why Xerces is making things difficult.
A possible solution can be found here.
3,276,973
3,763,151
How to show (printer) dialog boxes in Windows CE Direct-X app?
This page says you need to call PrintSetupDlg, but this code PAGESETUPDLG printDialog; ZeroMemory(&printDialog, sizeof(printDialog)); printDialog.lStructSize = sizeof(printDialog); printDialog.hwndOwner = hwnd; //or = NULL PageSetupDlg(&printDialog); freezes the program on the call to PageSetupDlg - it becomes unresponsive, and I need to stop the process. How do I print in Windows CE? (using C++ in a DirectX app, CE 6.0)
Turns out that, for some crazy reason, dialog boxes only get drawn to the original front buffer, even if that buffer has been swapped and the original back buffer is now the front buffer (being shown on the screen). The solution was to keep track of how many times the buffer has been swapped, and swap it again if the number of swaps was odd (which causes the original front buffer to always be the current front-buffer when the dialog is shown).
3,277,058
3,277,094
How to rollback lines from cout?
I'm coding a task monitoring, which updates tasks' progress using cout. I'd like to display one task progress per line, therefore I have to rollback several lines of the console. I insist on "several" because \b does the job for one line, but does not erase \n between lines. I tried std::cout.seekp(std::cout.tellp() - str.length()); but tellp() returns -1 (failure).
You can do cout << '\r'; to jump to the beginning of the current line, but moving upwards is system-specific. For Unix, see man termcap and man terminfo (and search for cursor_up). On ANSI-compatible terminals (such as most modern terminals available on Unix), this works to move up: cout << "\e[A";. Don't try seeking in cout, it's unseekable most of the time (except when redirected to a file). As mentioned in other answers, using the ncurses (or slang) library provides a good abstraction for terminal I/O on Unix. Instead of filling with spaces (which is error-prone, because not every terminal is 80 characters wide), you can do \r + clr_eol: std::cout << "\r\e[K" << std::flush.
3,277,121
3,277,149
include objective-c header in c++ file
Is there a way to include an objective-c header from a cpp? Because when I try to #include "cocos2d.h" from a cpp .h file, a lot of errors complaining about @'s and -'s are showing up. Can c++ files include obj-c headers like that?
It is possible, but you need to use Objective-C++ (e.g. by making the file extension .mm) to mix the languages, plain C++ sources don't work. To make that clear: .m files only allow Objective-C sources .cpp files only allow C++ sources .mm allow mixed Objective-C++ sources - i.e. both Objective-C and C++ with some limitations If you need to keep the two worlds seperated instead you need to write wrapper classes that hides the Objective-C details from C++ and vice versa.
3,277,172
3,277,183
Using pair as key in a map (C++ / STL)
I want to use a pair from STL as a key of a map. #include <iostream> #include <map> using namespace std; int main() { typedef pair<char*, int> Key; typedef map< Key , char*> Mapa; Key p1 ("Apple", 45); Key p2 ("Berry", 20); Mapa mapa; mapa.insert(p1, "Manzana"); mapa.insert(p2, "Arandano"); return 0; } But the compiler throw a bunch of unreadable information and I'm very new to C and C++. How can I use a pair as a key in a map? And in general How can I use any kind of structure (objects, structs, etc) as a key in a map? Thanks!
std::map::insert takes a single argument: the key-value pair, so you would need to use: mapa.insert(std::make_pair(p1, "Manzana")); You should use std::string instead of C strings in your types. As it is now, you will likely not get the results you expect because looking up values in the map will be done by comparing pointers, not by comparing strings. If you really want to use C strings (which, again, you shouldn't), then you need to use const char* instead of char* in your types. And in general How can I use any kind of structure (objects, structs, etc) as a key in a map? You need to overload operator< for the key type or use a custom comparator.
3,277,179
3,277,195
Problems importing a .lib into another project
I'm using Visual Studio 2008 under Windows 7. I have a .lib and accompanying .h files (which make use of wxWidgets if that makes a difference) which compile without any issues. I'm trying to import that library into a GUI project but when I do, the main class I'm interested in doesn't appear to be there? I've added #include "MyLib.h" to the gui and added mylib.lib to the including libraries but for some reason I get: MyLib.obj : error LNK2001: unresolved external symbol "public: __thiscall MyLibClass::MyLibClass(void)" (??0MyLibClass@@QAE@XZ) Why might that happen?
Maybe are you referencing an old version of the library? Are you sure the linked libraries in the project settings are set to the right path?
3,277,376
3,277,400
Is Python-based software considered less-professional than C++/compiled software?
I'm working on a plugin for some software that I'm planning on selling someday. The software I'm making it for has both a C++ SDK and a Python SDK. The C++ SDK documentation appears incomplete in certain areas and isn't documented that well. The Python SDK docs appear more complete and in general are much easier to work with. So I'm trying to decide if I want to go through the potential trouble of building a C++ plugin instead of a Python plugin to sell. About the only thing that makes me want to do a C++ plugin is that in my mind, a "C++ plugin" might be an easier sell than a "Python plugin". A lot of programmers out there don't even considered writing Python to be real "programming". Do you think that potential customers might say "Why would I pay money for a measly little Python script?"? As opposed to "Oh it was written in C++ so the guy must be a decent programmer"? Writing the Python plugin would be faster. Both plugins would look and behave exactly the same. The C++ plugin might be faster in certain spots, but for the type of plugin this is, that's not a huge deal. So my question is, would a Python plugin be considered not as professional/sellable as a C++ plugin, even if it looks and acts EXACTLY the same as a C++ plugin?
A lot of programmers out there don't even considered writing Python to be real "programming". A lot of "programmers" out there are incompetent, too. Do you think that potential customers might say "Why would I pay money for a measly little Python script?"? I'm sure it depends on the type of software, but I can tell you that my program's customers have little interest in what we use to develop our product, and I doubt most of them know that the software is written in C++. They just care that it works. So my question is, would a Python plugin be considered not as professional/sellable as a C++ plugin, even if it looks and acts EXACTLY the same as a C++ plugin? No.
3,277,717
3,277,779
C++ WinAPI: handling long file paths/names
I'm looking at handling longer file paths in my windows application. Currently, I have a text box (edit box) in which a user can type an absolute file path. I then read that typed file path, using GetWindowText, into a string declared like so: TCHAR FilePath[MAX_PATH]; Obviously, here i'm relying on the MAX_PATH constant which limits me to 260 chars. So to handle longer file/paths names could I just extend my TCHAR array like this: TCHAR FilePath[32767];. Or is there a better way? Could I use a variable length array? (TCHAR FilePath[]; is this even possible in C++? - sorry i'm pretty new to this). Thank you in advanced! Here's the whole code snippet of what i mentioned above: TCHAR FilePath[MAX_PATH]; ZeroMemory(&FilePath, sizeof(FilePath)); GetWindowText(hWndFilePath, FilePath, MAX_PATH);
There are a number of limitations with respect to file paths on Windows. By default, paths cannot be longer than 260 characters, which is what the MAX_PATH constant is for. However, you can access longer paths - with certain limitations - by prefixing the path with "\\?\". However, the limitations of using the "\\?\" prefix usually outweighs the benefit: There are a number of Win32 APIs that do no support paths with this prefix (for example, LoadLibrary will always fail on a path that is longer than 260 characters) The Win32 Canonicalization rules do not take effect when using the "\\?\" prefix. For example, by default, "/" in paths is converted to "\", "." and ".." are converted into references to the current and parent directories respectively and so on: none of that happens when you use the "\\?\" prefix. Just because you can modify your program to support longer paths, other programs may fail to open the files you've created. This will be the case if those other programs don't also use the "\\?\" prefix. To be honest, point #2 is the real killer: you open yourself up to all sorts of trouble when using the "\\?\" prefix and you basically have to re-implement the Win32 canonicalization rules yourself if you go that route. Therefore, my recommendation is to just stick with the 260 limitation. At least until there's better platform support for longer paths.
3,277,756
3,277,773
C++ noob question: pointers and overloaded []
I've been staring at this for a while and not getting very far. FruitBasketFactory, FruitBasket, and Fruit are three classes from an API I'm using. My goal is to make a fruit basket and then retrieve the fruit. According to the FruitBasketFactory.hpp: const FruitBasket* getFruitBasket() const; and then in the FruitBasket.hpp size_t getNumFruits() const; const Fruit& operator[](size_t index) const; So here's my initial code: FruitBasketFactory fruitBasketFactory; //since I want an object rather than a pointer I attempt to dereference the pointer const FruitBasket fruitBasket = *(fruitBasketFactory.getFruitBasket()); But here I get an error "error C2248: 'FruitBasket::FruitBasket' : cannot access private member declared in class 'FruitBasket'". Shouldn't this work? So, fine... I rework my code. FruitBasketFactory fruitBasketFactory; const FruitBasket* fruitBasket = fruitBasketFactory.getFruitBasket(); if(fruitBasket->getNumFruits() > 0) { //using (*fruitBasket)[0] seems silly const Fruit fruit = (*fruitBasket)[0]; } And fail: "error C2248: 'Fruit::Fruit' : cannot access private member declared in class 'Fruit'" So, another rework FruitBasketFactory fruitBasketFactory; const FruitBasket* fruitBasket = fruitBasketFactory.getFruitBasket(); if(fruitBasket->getNumFruits() > 0) { //this is just ludicrous ... I'm doing something wrong const Fruit* fruit = &(fruitBasket->operator[](0)); } As goofy as this piece of code looks, it actually works. But why can I just do what I think should be the most obvious thing? FruitBasketFactory fruitBasketFactory; const FruitBasket fruitBasket = *(fruitBasketFactory.getFruitBasket()); if(fruitBasket.getNumFruits() > 0) { const Fruit fruit = fruitBasket[0]; } Resolution: The copy constructors were indeed blocked for both FruitBasket and Fruit. I was able to get around calling them by creating references as follows: FruitBasketFactory fruitBasketFactory; const FruitBasket& fruitBasket = *(fruitBasketFactory.getFruitBasket()); if(fruitBasket.getNumFruits() > 0) { const Fruit& fruit = fruitBasket[0]; }
But here I get an error error C2248: 'FruitBasket::FruitBasket' : cannot access private member declared in class 'FruitBasket'. The copy constructor for FruitBasket is inaccessible. Have you declared the copy constructor for this class as private or protected? Does this class have any bases or members that are not copyable (i.e., that do not have publicly accessible copy constructors)? To answer your last question, this: const Fruit* fruit = &(fruitBasket->operator[](0)); can be much more reasonably written as this: const Fruit* fruit = &(*fruitBasket)[0]; The pointer must be dereferenced so that the subscript operator is applied to the class-type FruitBasket object and not to the pointer to the FruitBasket. If you apply the subscript of the pointer, the built-in subscript operator is used and the pointer is treated as a pointer to an array of FruitBasket objects.
3,277,823
3,277,833
Appropriate use of friend? Container class designed to manipulate objects of specific type
Lets say you have a FooManager made to manage multiple objects of type Foo. The FooManager needs to see some parts of its Foos to evaluate their current state. Before I was using a few accessors in Foo to see these parts, until I realized that FooManager is the only class actually using these. I decided to make FooManager a friend of Foo. This resulted in most of class Foo becoming private. Is this an appropriate use of friend? My reasoning was that it helps encapsulation because while it gives FooManager complete access to Foo's internals, it completely blocks off access to everything else.
Unless there is a different and cleaner way to achieve what you're trying to achieve, this sounds like a fair approach. With regards to encapsulation, see: http://www.parashift.com/c++-faq-lite/friends.html#faq-14.2.
3,277,842
3,277,953
How to get rid of padding bytes between data members of a struct
I have a binary file with "messages" and I am trying to fit the bytes inside the right variable using structs. In my example I used two types of messages: Tmessage and Amessage. #include <iostream> #include <fstream> #include <stdlib.h> #include <string> #include <iomanip> using namespace std; struct Tmessage { unsigned short int Length; char MessageType; unsigned int Second; }; struct Amessage { unsigned short int Length; char MessageType; unsigned int Timestamp; unsigned long long int OrderReferenceNumber; char BuySellIndicator; unsigned int Shares; char Stock[6]; unsigned int Price; }; int main(int argc, char* argv[]) { const char* filename = argv[1]; fstream file(filename, ios::in | ios::binary); unsigned long long int pi = 0; if(file.is_open()){ cout << filename << " OPENED" << endl; } else { cout << "FILE NOT OPENED" << endl; } unsigned char* memblock; memblock = new unsigned char[128]; file.read((char *)memblock, 128); cout << "BINARY DATA" << endl; while (pi < 128) { cout << setw(2) << hex << static_cast<unsigned int>(memblock[pi]) << " "; pi++; if((pi%16)==0) cout << endl; } unsigned int poi = 0; Tmessage *Trecord; Trecord = (Tmessage *)memblock; cout << "Length: " << hex << (*Trecord).Length << endl; cout << "Message type: " << hex << (*Trecord).MessageType << endl; cout << "Second: " << hex << (*Trecord).Second << endl; poi = poi + 7; cout << endl; Amessage *Arecord; Arecord = (Amessage *)(memblock+poi); cout << "Length: " << hex << (*Arecord).Length << endl; cout << "Message type: " << hex << (*Arecord).MessageType << endl; cout << "Timestamp: " << hex << (*Arecord).Timestamp << endl; cout << "OrderReferenceNumber: " << hex << (*Arecord).OrderReferenceNumber << endl; cout << "BuySellIndicator: " << hex << (*Arecord).BuySellIndicator << endl; cout << "Shares: " << hex << (*Arecord).Shares << endl; cout << "Stock: " << hex << (*Arecord).Stock << endl; cout << "Price: " << hex << (*Arecord).Price << endl; delete memblock; file.close(); cout << endl << "THE END" << endl; return 0; } The output when I run the program: stream OPENED BINARY DATA 0 5 54 0 0 62 72 0 1c 41 0 f 42 40 0 0 0 0 0 4 2f 76 53 0 0 3 e8 53 50 59 20 20 20 0 11 5 d0 0 1c 41 0 f 42 40 0 0 0 0 0 4 2f 78 42 0 0 3 e8 53 50 59 20 20 20 0 10 f7 5c 0 1c 41 0 f 42 40 0 0 0 0 0 4 2f 90 53 0 0 1 2c 53 50 59 20 20 20 0 11 2 b0 0 5 54 0 0 62 76 0 d 44 14 25 78 80 0 0 0 0 0 4 2f 90 0 d 44 14 25 78 80 0 0 Length: 500 Message type: T Second: 726200 Length: 1c00 Message type: A Timestamp: 40420f OrderReferenceNumber: 53762f0400000000 BuySellIndicator: Shares: 20595053 Stock: Price: 420f0041 THE END The program places the bytes inside the Tmessage struct correctly. (0 5 54 0 0 62 72) However, something occurs while parses Amessage. (0 1c 41 0 f 42 40 0 0 0 0 0 4 2f 76 53 0 0 3 e8 53 50 59 20 20 20 0 11 5 d0) The Lenght, MessageType and Timestamp are correct but OrderReferenceNumber contains the "53" byte which belongs to BuySellIndicator and then the other variable are incorrect. The correct A message output should be: Length: 1c 0 Message type: 41 Timestamp: 40 42 f 0 OrderReferenceNumber: 76 2f 4 0 0 0 0 0 BuySellIndicator: 53 Shares: e8 3 0 0 Stock: 53 50 59 20 20 20 Price: d0 5 11 0 The 2 questions: a) Why the OrderReferenceNumber contains the "53" byte? b) I think that "char Stock[6]" does not work, because between Share's bytes and Price's bytes there are more than 6 bytes. How can I fit the 6 bytes into the char vector or string? Note: I am aware that I have to swap the bytes because the binary data comes in big-endian. That is why "Stock" should not be swapped. Thank you very much for your help! Kind regards,
The compiler is probably inserting pad bytes between members of your struct. One way you can get around this is to use pragma pack. Note that this is non-standard, but it works on g++ and visual C++. #pragma pack (push, 1) struct Amessage { unsigned short int Length; char MessageType; unsigned int Timestamp; unsigned long long int OrderReferenceNumber; char BuySellIndicator; unsigned int Shares; char Stock[6]; unsigned int Price; }; #pragma pack (pop) What's going on in the code above is: the pragma pack tells the compiler you don't want it to insert padding to make it so that it'll be performing aligned access to members of the struct. the push/pop thing is so you can have nested #pragma packs (for example, when including header files) and have a way to go back to the previously set pack options. See MSDN for an explanation that's probably better than the one I could give. http://msdn.microsoft.com/en-us/library/2e70t5y1%28VS.80%29.aspx
3,277,961
3,277,970
How can I safely (and easily) count *all* instances of a class within my program?
I would like to be able to instantiate a particular (and otherwise normal) class (the source of which I can modify) and count the number of times the class has been instantiated (e.g. like this). But I would like to include all instances in my total count, even some which are created via the copy constructor in standard containers. Would it be appropriate to have all the constructors (including the copy constructor) of my class increment a static counter? If so, is it possible to ensure my class still conforms to the requirements of standard containers (i.e., T(x) is equivalent to x), by overriding other operators for example?
Think of the static class variable as a global variable which is just in the namespace of the class. Incrementing or doing other things with it will not have any side effects on other code, i.e. your constructors and other operators will behave exactly as before. I.e., you are right: Just increment in all constructors and decrement in the destructor. Of course, as George pointed out, if you want to have it multithreading safe, you need to add some multithreading safe code around the access to your counter variable (for example some mutex). Or as Steven pointed out, you might also use atomic increment/decrement instructions (but the usage will depend on the platform). Those would be a lot faster. Though, you have to be careful because in some cases that wont work in multi-processor environments. You can use Boost's atomic_count to be on the safe side.
3,278,036
3,278,059
What are the problems with this producer/consumer implementation?
So I'm looking at using a simple producer/consumer queue in C++. I'll end up using boost for threading but this example is just using pthreads. I'll also end up using a far more OO approach, but I think that would obscure the details I'm interested in at the moment. Anyway the particular issues I'm worried about are Since this code is using push_back and pop_front of std::deque - it's probably doing allocation and deallocation of the underlying data in different threads - I believe this is bad (undefined behaviour) - what's the easiest way to avoid this? Nothing is marked volatile. But the important bits are mutex protected. Do I need to mark anything as volatile and if so what? - I don't think I do as I believe the mutex contains appropriate memory barriers etc., but I'm unsure. Are there any other glaring issues? Anyway heres the code: #include <pthread.h> #include <deque> #include <iostream> struct Data { std::deque<int> * q; pthread_mutex_t * mutex; }; void* producer( void* arg ) { std::deque<int> &q = *(static_cast<Data*>(arg)->q); pthread_mutex_t * m = (static_cast<Data*>(arg)->mutex); for(unsigned int i=0; i<100; ++i) { pthread_mutex_lock( m ); q.push_back( i ); std::cout<<"Producing "<<i<<std::endl; pthread_mutex_unlock( m ); } return NULL; } void* consumer( void * arg ) { std::deque<int> &q = *(static_cast<Data*>(arg)->q); pthread_mutex_t * m = (static_cast<Data*>(arg)->mutex); for(unsigned int i=0; i<100; ++i) { pthread_mutex_lock( m ); int v = q.front(); q.pop_front(); std::cout<<"Consuming "<<v<<std::endl; pthread_mutex_unlock( m ); } return NULL; } int main() { Data d; std::deque<int> q; d.q = &q; pthread_mutex_t mutex; pthread_mutex_init( &mutex, NULL ); d.mutex = & mutex; pthread_t producer_thread; pthread_t consumer_thread; pthread_create( &producer_thread, NULL, producer, &d ); pthread_create( &consumer_thread, NULL, consumer, &d ); pthread_join( producer_thread, NULL ); pthread_join( consumer_thread, NULL ); } EDIT: I did end up throwing away this implementation, I'm now using a modified version of the code from here by Anthony Williams. My modified version can be found here This modified version uses a more sensible condition variable based approach.
It is perfectly valid to allocate memory in one thread and free it in another if both threads are in the same process. Using a mutex to protect access to the deque should provide the correct memory access configuration. EDIT: The only other thing to think about is the nature of the producer and consumer. Your synthesized example lacks some of the subtleties involved with a real implementation. For example, how will you synchronize the producer with the consumer if they are not operating at the exact same rate? You might want to consider using something like a pipe or an OS queue instead of a deque so that the consumer can block on read if there is no data ready to process.
3,278,314
3,278,346
How to marshall c++ char* to C# string using P/INVOKE
I'm new to C++. I'm calling a C++ function from C# using a PINVOKE and wanting to get a string back as an out parameter. However I just get an empty string back. The int out parameter works fine. Importing: [DllImport ( @"UnamanagedAssembly.dll", CharSet = CharSet.Ansi)] public static extern int Activate(ref int numActivated, StringBuilder eventsActivated); extern "C" __declspec(dllexport) int Activate(int *p_NumActivated, char *p_EventsActivated) {return Activation::GetInstance()->Activate(p_NumActivated, p_EventsActivated);} Calling my C++ function from C#: int numActivated = 0; StringBuilder eventsActivated = new StringBuilder(); int status = Activate(ref numActivated, eventsActivated); The C++ function: int Activation::Activate(int *p_NumActivated, char *&p_EventsActivated) { char *pTemp = "Hello"; p_EventsActivated = pTemp; *p_NumActivated = 1; return 0; }
[DllImport ( @"UnamanagedAssembly.dll", CharSet = CharSet.Ansi)] public static extern int Activate( ref int numActivated, [MarshalAs(UnmanagedType.LPStr)]StringBuilder eventsActivated);
3,278,600
3,278,657
Do I need to define `operator==` to use my class with standard containers?
I'd like clarification on the C++ standard, specifically where it says (my interpretation) in section 20.1.3 that "for class T and an instance of class T called x, T(x) must be equivalent to x" for the class to work with standard containers. I couldn't find a definition of 'equivalent'. Does this mean that I have to define operator== as a member of my class, so that T(x) == x returns true?
Equivalent is purposefully vague. (To avoid things like implying operator== must be defined; it doesn't in a general case.) However, conceptually two things are equivalent if their data represents the same object. If a class has data that might be different when "copied", then you do need to make an operator== (and possibly operator< along with rel_ops) to make sure that "equivalent" is implemented with respect to that. (Effectively, make sure that the mutable data isn't 'part of the class', so to speak.) It's usually better not to go such a route, because you end up having to patch lots of things up to make sure it works properly. If something is to be copied, let if be fully copied. This makes much more sense.
3,278,625
3,278,636
When do we have to use copy constructors?
I know that C++ compiler creates a copy constructor for a class. In which case do we have to write a user-defined copy constructor? Can you give some examples?
The copy constructor generated by the compiler does member-wise copying. Sometimes that is not sufficient. For example: class Class { public: Class( const char* str ); ~Class(); private: char* stored; }; Class::Class( const char* str ) { stored = new char[srtlen( str ) + 1 ]; strcpy( stored, str ); } Class::~Class() { delete[] stored; } in this case member-wise copying of stored member will not duplicate the buffer (only the pointer will be copied), so the first to be destroyed copy sharing the buffer will call delete[] successfully and the second will run into undefined behavior. You need deep copying copy constructor (and assignment operator as well). Class::Class( const Class& another ) { stored = new char[strlen(another.stored) + 1]; strcpy( stored, another.stored ); } void Class::operator = ( const Class& another ) { char* temp = new char[strlen(another.stored) + 1]; strcpy( temp, another.stored); delete[] stored; stored = temp; }
3,278,862
3,283,815
Any obvious problems or improvements for my producer consumer queue
I asked a previous question about producer/consumer code that was overly general (though the answers were certainly helpful). So I've taken the suggestions from an earlier SO question by another author and converted them to C++ and boost. However I'm always a bit concerned about multithreaded code - so if anyone can see any obvious improvements I'd love to hear about them. #include <pthread.h> #include <deque> #include <iostream> #include "boost/thread.hpp" class MyQueue { protected: boost::mutex mutex_; boost::condition_variable condition_; bool cancel_; std::deque<int> data_; public: MyQueue() : mutex_(), condition_(), cancel_(false), data_() { } struct Canceled{}; void push( int i ) { boost::lock_guard<boost::mutex> l(mutex_); if(cancel_) throw Canceled(); data_.push_back(i); condition_.notify_all(); } void pop( int & i ) { boost::unique_lock<boost::mutex> l(mutex_); while(! cancel_ && data_.size()==0 ) { condition_.wait( l ); } if(cancel_) throw Canceled(); assert( data_.size() != 0 ); i = data_.front(); data_.pop_front(); } void cancel() { boost::lock_guard<boost::mutex> l(mutex_); if( cancel_) throw Canceled(); cancel_ = true; condition_.notify_all(); } }; boost::mutex iomutex; void producer( MyQueue * q, const std::string & name ) try { for(unsigned int i=0 ; i<20; ++i) { q->push( i ); boost::lock_guard<boost::mutex> l(iomutex); std::cout<<name<<" PRODUCED "<<i<<std::endl; } sleep(1); q->cancel(); { boost::lock_guard<boost::mutex> l(iomutex); std::cout<<name<<" PRODUCER EXITING NORMALLY"<<std::endl; } } catch( MyQueue::Canceled & c ) { boost::lock_guard<boost::mutex> l(iomutex); std::cout<<name<<" PRODUCER CANCLED "<<std::endl; } void consumer( MyQueue * q, const std::string & name ) try { while(true) { int i; q->pop( i ); boost::lock_guard<boost::mutex> l(iomutex); std::cout<<name<<" CONSUMED "<<i<<std::endl; } } catch( MyQueue::Canceled & c ) { boost::lock_guard<boost::mutex> l(iomutex); std::cout<<name<<" CONSUMER CANCLED "<<std::endl; } int main() { MyQueue q; boost::thread pr1( producer, &q, "pro1"); boost::thread pr2( producer, &q, "pro2"); boost::thread cons1( consumer, &q, "con1"); boost::thread cons2( consumer, &q, "con2"); pr1.join(); pr2.join(); cons1.join(); cons2.join(); } UPDATE: I ended up using a modified version of Anthony Williams' concurrent queue. My modified version can be found here.
If you're worried about potential pitfalls in your implementation, you can try using Anthony Williams' (maintainer of the Boost.Thread library) excellent thread-safe, multiple-producer, multiple-consumer queue.
3,278,864
3,278,924
What is the difference between header file and namespace?
I want to know the exact difference between Header file (as in MyHeader.hpp) and a namespace in c++?
Header files are actual files - stored in the file system, referenced by file name, and #include'd in other files (at least, in C/C++ or other languages using the M4 macro preprocessor). Header files typically group pieces of code that are all interdependent parts of the same specific item together. For instance, a game might have a header file for all of its graphics rendering. Namespaces, on the other hand, are an element of the programming language - they don't exist as a file system object, but rather as a designation within code telling the compiler that certain things are within that namespace. Namespaces typically group interfaces (functions, classes/structs, types) of similar (but not necessarily interdependent) items. For instance, the std namespace in C++ contains all of the Standard Library functions and classes.
3,279,014
3,279,360
Trying to understand the C preprocessor
Why do these blocks of code yield different results? Some common code: #define PART1PART2 works #define STRINGAFY0(s) #s #define STRINGAFY1(s) STRINGAFY0(s) case 1: #define GLUE(a,b,c) a##b##c STRINGAFY1(GLUE(PART1,PART2,*)) //yields "PART1PART2*" case 2: #define GLUE(a,b) a##b##* STRINGAFY1(GLUE(PART1,PART2)) //yields "works*" case 3: #define GLUE(a,b) a##b STRINGAFY1(GLUE(PART1,PART2*)) //yields "PART1PART2*" I am using MSVC++ from VS.net 2005 sp1 Edit: it is currently my belief that the preprocessor works like this when expanding macros: Step 1: - take the body - remove any whitespace around ## operators - parse the string, in the case that an identifier is found that matches the name of a parameter: -if it is next to a ## operator, replace the identifier with the literal value of the parameter (i.e. the string passed in) -if it is NOT next to a ## operator, run this whole explanation process on the value of the parameter first, then replace the identifier with that result. (ignoring the stringafy single '#' case atm) -remove all ## operators Step 2: - take that resultant string and parse it for any macros now, from that I believe that all 3 cases should produce the exact same resultant string: PART1PART2* and hence after step 2, should result in works* but at very least should result in the same thing.
cases 1 and 2 have no defined behavior since your are tempting to paste a * into one preprocessor token. According to the association rules of your preprocessor this either tries to glue together the tokens PART1PART2 (or just PART2) and *. In your case this probably fails silently, which is one of the possible outcomes when things are undefined. The token PART1PART2 followed by * will then not be considered for macro expansion again. Stringfication then produces the result you see. My gcc behaves differently on your examples: /usr/bin/gcc -O0 -g -std=c89 -pedantic -E test-prepro.c test-prepro.c:16:1: error: pasting "PART1PART2" and "*" does not give a valid preprocessing token "works*" So to summarize your case 1 has two problems. Pasting two tokens that don't result in a valid preprocessor token. evaluation order of the ## operator In case 3, your compiler is giving the wrong result. It should evaluate the arguments to STRINGAFY1 to do that it has to expand GLUE GLUE results in PART1PART2* which must be expanded again the result is works* which then is passed to STRINGAFY1
3,279,095
3,279,313
C++ Multiple Callback functions
I have a dll which requires me to set a callback function for it (actually it's a camera sdk and it will callback my function when it receives a picture). I want to have multiple (user input) cameras but I can't. Since I should make unknown number of callback functions. The easy way is to make a class (camera) which have a function for its callback. but I cannot pass the pointer of member of the class to the dll (it only accept (void)(image*)) Any possible solution?
Does camera SDK support multiple cameras connection? If not, you need to talk with SDK provider. If SDK supports multiple connection, it must provide the way to recognize the camera in callback function. But actual answer is in SDK itself. What is the "image" type, maybe it contains camera ID? Maybe camera ID is supplied when a client code makes callback subscription? Something like this: void Callback0(image*); void Callback1(image*); SubscribeImageCallback(0, Callback0); // camera 0 SubscribeImageCallback(1, Callback1); // camera 1 Actual answer to your question depends on the camera SDK interface.
3,279,158
3,279,336
C++: How to implement (something like) JSON
Not sure how to explain it - I'm pretty new to C++, but... let me try: Let's say I have 300+ names (Jeff, Jack...) with 300+ int values (0 or 1). In JS I would use JSON. Something like this: var people = {"person": [ {"name": "Jeff","val": 0}, {"name": "Jill","val": 1}, {"name": "Jack","val": 0}, {"name": "Jim","val": 1}, {"name": "John","val": 0} ]} What's the best way to do this in C++? Thanks.
If you can have duplicate names you can't use a map, so you could use something like this: struct Person { Person( const std::string & n, int v ) : name(n), val(v) {} std::string name; int val; }; int main() { std::vector<Person> people; people.push_back( Person( "Jeff", 0 ) ); people.push_back( Person( "Jill", 1 ) ); ... } If you wanted uniqueness of names you could do something like this: std::map<std::string, int> people; people["Jeff"] = 0; people["Jill"] = 1; or std::map<std::string, Person> people; people["Jeff"] = Person("Jeff",0); people["Jill"] = Person("Jill",1); If you're using this code a lot you can clean up the repeated cruft. template<typename K, typename V> struct BuildMap { BuildMap() : map_() {} BuildMap<K,V>& operator()( const K & key, const V & value ) { map_[key]=value; return *this; } std::map<K,V> operator()() { return map_; } std::map<K,V> map_; }; std::map<std::string,int> people = BuildMap<std::string,int>() ( "Jeff", 0 ) ( "Jill", 1 ) ( "John", 1 ) (); Hope this gives you some ideas.
3,279,319
3,279,343
Determine inheritance at compile time
I have some code that behaves like this: class Base {}; class MyClass : public Base {}; MyClass* BaseToMyClass(Base* p) { MyClass* pRes = dynamic_cast<MyClass*>(p); assert(pRes); return pRes; } Is there a way to add a compile time check so I can catch calls to this function where p is not an instance of MyClass? I had a look at Alexandrescu's SUPERSUBCLASS function but I'm not sure if it can do the job. Thanks!
Is there a way to add a compile time check so I can catch calls to this function where p is not an instance of MyClass? Generally, if you want to check this at compile-time, you'd take the derived class as an argument. However, if the only thing you have is a Base* or a Base&, then you cannot know whether it refers to a MyClass object. It's the very nature of run-time polymorphism that this is to be found out at run-time. This check can only be done where the MyClass object/reference/pointer is converted to a Base*/Base&. That's why dynamic_cast<>() was invented. Your function basically is a safe_cast. If you put it into the right syntax, it looks like this: template< typename Derived, typename Base > inline Derived* safe_cast(Base* pb) { #if defined _NDEBUG return static_cast<Derived*>(pb); #else Derived* pd = dynamic_cast<Derived*>(pb); assert(pd); return pd; #endif } template< typename Derived, typename Base > inline Derived& safe_cast(Base& rb) { return *safe_cast<Derived*>(&rb); }
3,279,733
3,280,304
ofstream doesn't write buffer to file
I'm trying to write the contents of buf pointer to the file created by ofstream. For some reason the file is empty, however the contents of buf is never empty... What am I doing wrong? void DLog::Log(const char *fmt, ...) { va_list varptr; va_start(varptr, fmt); int n = ::_vscprintf(fmt, varptr); char *buf = new char[n + 1]; ::vsprintf(buf, fmt, varptr); va_end(varptr); if (!m_filename.empty()) { std::ofstream ofstr(m_filename.c_str(), ios::out); ofstr << *buf; // contents of *buf are NEVER empty, however nothing is in file?? ofstr.close(); } delete [] buf; }
Many problems can be solved by getting rid of the hairy stuff, like manual allocation management. Never use new T[N] in your code: instead use std::vector<T> v(N);. Simply this alone might solve your problem, because the pointer stuff isn't in the way: void DLog::Log(const char *fmt, ...) { va_list varptr; va_start(varptr, fmt); int n = ::_vscprintf(fmt, varptr); std::vector<char> buf(n + 1); ::vsprintf(&buf[0], fmt, varptr); va_end(varptr); if (!m_filename.empty()) { std::ofstream ofstr(m_filename.c_str(), ios::out); if (!ofstr) { // didn't open, do some error reporting here } // copy each character to the stream std::copy(buf.begin(), buf.end(), std::ostream_iterator<char>(ofstr)); // no need to close, it's done automatically } // no need to remember to delete } Much easier to read and maintain. Note even better would be a std::string buf(n + 1);, then you could just do ofstr << buf;. Sadly, std::string isn't currently required to store its elements contiguously, like std::vector. This means the line with &buf[0] isn't guaranteed to work. That said, I doubt you'll find an implementation where it wouldn't work. Still, it's arguably better to maintain guaranteed behavior. I do suspect the issue was you dereferencing the pointer, though.
3,279,781
3,309,137
Forward declaring classes in namespaces
I was rather surprised to learn that I couldn't forward declare a class from another scope using the scope resolution operator, i.e. class someScope::someClass; Instead, the full declaration has to be used as follows: namespace { class someClass; } Can someone explain why this is the case? UPDATE: To clarify, I am asking why this is the case.
Seems as though the answer lies in the C++ specification: 3.3.5 "Namespace scope" in the standard. Entities declared in a namespace-body are said to be members of the namespace, and names introduced by these declarations into the declarative region of the namespace are said to be member names of the namespace. A namespace member can also be referred to after the :: scope resolution operator (5.1) applied to the name of its namespace or the name of a namespace which nominates the member’s namespace in a using-directive;
3,279,869
3,281,369
why is this syntax exclusively used to initialize string literals and can't be used for an array of characters?
Possible Duplicate: initializing char arrays in a way similar to initializing string literals below is a sample of initializing a string literal in which a terminating null character is added at the end of string, necessarily: char reshte[]="sample string"; I wonder why can't we initialize an array of characters without terminating null character, in that way and we have to use the following syntax instead, that is exhausting in case there is a large number of characters: char reshte[]={'s','a','m','p','l','e',' ','s','t','r','i','n','g'};
I don't understand why you need the string without the terminating character so badly. Storage/performance wise, it doesn't make it an issue. You can just work knowing there's a null character at the end you don't need for your application, if you want to use that instantiation. Or you could maybe do something like: char reshte[]="sample strin"; reshte[strlen(reshte)]='g';
3,279,897
3,279,926
Convert vector<char> buf(256) to LPCSTR?
Is there a way to convert the above? If so what is the best way? I guess you can loop through the vector and assign to a const char*, but I'm not sure if that is the best way.
std::string s(vec.begin(), vec.end()); // now use s.c_str() I think this should be fairly safe.
3,280,197
3,383,899
What's the best way to demonstrate the effect of affinity setting?
Once I noticed that Windows doesn't keep computation-intensive threads on a specific core - it keeps switching cores instead. So I speculated that the job would be done faster, if the thread would keep access to the same data caches. And really, I was able to observe a stable ~1% speed improvement after setting the thread's affinity mask to a single core (in a ppmd (de)compression thread). But then I tried to build a simple demo for this effect, and more or less failed - that is, it works as expected on my system (Q9450): buflog=21 bufsize=2097152 (cache flush) first run = 6.938s time with default affinity = 6.782s time with first core only = 6.578s speed gain is 3.01% but people I asked weren't exactly able to reproduce the effect. Any suggestions? #include <stdio.h> #include <windows.h> int buflog=21, bufsize, bufmask; char* a; char* b; volatile int r = 0; __declspec(noinline) int benchmark( char* a ) { int t0 = GetTickCount(); int i,h=1,s=0; for( i=0; i<1000000000; i++ ) { h = h*200002979 + 1; s += ((int&)a[h&bufmask]) + ((int&)a[h&(bufmask>>2)]) + ((int&)a[h&(bufmask>>4)]); } r = s; t0 = GetTickCount() - t0; return t0; } DWORD WINAPI loadcore( LPVOID ) { SetThreadAffinityMask( GetCurrentThread(), 2 ); while(1) benchmark(b); } int main( int argc, char** argv ) { if( (argc>1) && (atoi(argv[1])>16) ) buflog=atoi(argv[1]); bufsize=1<<buflog; bufmask=bufsize-1; a = new char[bufsize+4]; b = new char[bufsize+4]; printf( "buflog=%i bufsize=%i\n", buflog, bufsize ); CreateThread( 0, 0, &loadcore, 0, 0, 0 ); printf( "(cache flush) first run = %.3fs\n", float(benchmark(a))/1000 ); float t1 = benchmark(a); t1/=1000; printf( "time with default affinity = %.3fs\n", t1 ); SetThreadAffinityMask( GetCurrentThread(), 1 ); float t2 = benchmark(a); t2/=1000; printf( "time with first core only = %.3fs\n", t2 ); printf( "speed gain is %4.2f%%\n", (t1-t2)*100/t1 ); return 0; } P.S. I can post a link to compiled version if anybody needs that.
default affinity: (source: dreamhosters.com) affinity set to core #4 (source: dreamhosters.com) Now, this is an archiver. Do you really think that the worker thread going all around the cpu is ok?
3,280,410
3,280,465
Why doesn't delete destroy anything?
I'm playing a little with memory dynamic allocation, but I don't get a point. When allocating some memory with the new statement, I'm supposed to be able to destroy the memory the pointer points to using delete. But when I try, this delete command doesn't seem to work since the space the pointer is pointing at doesn't seem to have been emptied. Let's take this truly basic piece of code as an example: #include <iostream> using namespace std; int main() { //I create a pointer-to-integer pTest, make it point to some new space, // and fulfill this free space with a number; int* pTest; pTest = new int; *(pTest) = 3; cout << *(pTest) << endl; // things are working well so far. Let's destroy this // dynamically allocated space! delete pTest; //OK, now I guess the data pTest pointed to has been destroyed cout << *(pTest) << endl; // Oh... Well, I was mistaking. return 0; } Any clue ?
It's time to learn what undefined behavior is. :) In C++, when you do something illegal/nonsensical/bad/etc. the standard often says that "it leads to undefined behavior." This means that from that point forward, the state of your program is completely non-guaranteed, and anything could happen. At the point where you do your last *(pTest), you get undefined behavior. This is because pTest does not point to a valid object, and dereferencing such a pointer is undefined. So what you're seeing is totally allowed: undefined output. All you've done is said "I'm finished with this allocation." Once you've said that, you shouldn't (and indeed, cannot) inspect or care about that memory any longer. It doesn't even make conceptual sense to deallocate something then try to use it; you've said you were done! Your output is somewhat predictable though: likely, your OS simply says "okay, thanks for the memory" and that's it. It has no reason to actually "reset" the memory, or do anything special. That would indeed be a waste of time, when nobody (including your own program) is not using it. But remember, this output is completely undefined. Don't try to use objects that don't exist. Perhaps a better test would have been: #include <iostream> struct foo { ~foo() { std::cout << "foo is gone :(" << std::endl; } }; int main(void) { foo* f = new foo(); delete f; // you'll see that the object is destroyed. } Although it seems you were looking to see what happens with the memory itself. Just remember that it makes no sense to get rid of memory then try to use it, so the answer is: who knows. It's up to your specific platform, which C++ doesn't care about.
3,280,541
3,280,574
Perform vector operation
I'm using the vector container to store an array of doubles. Is there any quick way of multiplying each element in my vector by some scalar without using a loop. For example: vector<double> Array(10,1); will initialise an array of 10 doubles with initial value 1. To multiply this array by 0.5 I would write: for(unsigned int i=0; i<Array.size(); i++) Array[i] = 0.5*Array[i]; Is there there another way? I have used valarray which overloads the '*' operator so that: Array = 0.5 * Array; is valid but I'd rather not use valarray as it seems the vector container is a more standard approach for manipulating arrays. Thanks!
You could do this: std::transform(Array.begin(), Array.end(), Array.begin(), std::bind2nd(std::multiplies<double>(), 0.5)); In response to getting the sum of elements: double sum = std::accumulate(Array.begin(), Array.end(), 0.0); And in response to getting sqrt'ing each element: std::transform(Array.begin(), Array.end(), Array.begin(), static_cast<double (*)(double)>(std::sqrt)); That cast is to select the correct overload.
3,280,562
3,282,124
ctype and strings and containers
Is there any reason that the ctype facet functions (is,scan_is,scan_not only support plain char pointer, and not iterator based containers, like std::string or even a std::vector... then one could write: const ctype<char>& myctype = use_facet<std::ctype<char> >(locale("")); string foo_str = "hi there here is a number: 748574 and text again"; vector<char> foo(foo_str.begin(),foo_str.end()); //then one could write vector<char>::iterator num_begin_it = myctype.scan_is( ctype<char>::digit, foo.begin(), foo.end() ); vector<char> foo_num_1( foo, num_begin_it, myctype.scan_not(ctype<char>::digit, num_begin_it, foo.end() ); //instead of: const char* num_begin_pc = myctype.scan_is(ctype<char>::digit, &foo[0], &foo[foo.size()-1]+1); // &foo[foo.size()-1]+1) instead of foo.end() is not quite readable. vector<char> foo_num_2(num_begin_pc, myctype.scan_not(ctype<char>::digit, num_begin_pc, &foo[foo.size()-1]+1)); //appendix: //STL/Boost solution, even more verbose: function<bool(char)> is_digit_func = bind( mem_fn(static_cast<bool (ctype<char>::*)(ctype<char>::mask,char) const>(&ctype<char>::is)), &myctype, ctype<char>::digit, _1 ); vector<char>::iterator num_begin_0x = find_if(foo.begin(), foo.end(),is_digit_func); vector<char> foo_num_3(num_begin_0x,find_if(num_begin_0x, foo.end(),not1(is_digit_func))); // all 3 foo_num_X will now contain "748574" Would be cool if anyone has some insight why the standard committee made those design decisions ? And is there a better (=less verbose) way to make use of the ctype functions with iterator-based containers ? The STL/Boost solution would be kinda OK, if it wouldnt need that Additionally i found that there is no copy_if algorithm in the standard library, but i already the reason for this.
The main reason is that the Standard Library wasn't developed as a single coherent whole, but incorporates several libraries that were popular at the time. Iterators were a concept from the "Standard Template Library", which was the basis for the standard Containers, Iterators and Algorithms libraries. The Strings and Localization libraries came from other sources, which did not use iterators. Because iterators are so useful, it was deemed worth the effort of retrofitting them to these libraries, but not to completely change the libraries' interfaces to use iterators everywhere. By the way, you might find &foo.back()+1 or &foo[0] + foo.size() to be more readable than &foo[foo.size()-1]+1. You also don't need to copy the string into a vector to use scan_is and scan_not; something like this should do the job: const char* str_begin = foo_str.c_str(); const char* str_end = str_begin + foo_str.length(); const char* num_begin = myctype.scan_is(ctype<char>::digit, str_begin, str_end); const char* num_end = myctype.scan_not(ctype<char>::digit, num_begin, str_end); std::string number(num_begin, num_end); // or `vector` if you really want
3,280,738
3,280,845
How to write a makefile for a C++ project which uses Eigen, the C++ template library for linear algebra?
I'm making use of Eigen library which promises vectorization of matrix operations. I don't know how to use the files given in Eigen and write a makefile. The source files which make use of Eigen include files as listed below, these are not even header files (They are just some text files)- <Eigen/Core> <Eigen/Dense> <Eigen/Eigen> and so on. On Eigen's webpage, it's mentioned that, in order to use its functions I don't have to build the project, then how can I include these files in my makefile to build my project. My example main.c file looks like this. Can anyone show me how to write a makefile makefile for this file - #include <Eigen/Core> // import most common Eigen types USING_PART_OF_NAMESPACE_EIGEN int main(int, char *[]) { Matrix3f m3; m3 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix4f m4 = Matrix4f::Identity(); Vector4i v4(1, 2, 3, 4); std::cout << "m3\n" << m3 << "\nm4:\n" << m4 << "\nv4:\n" << v4 << std::endl; } Help!
According to Eigen's website, this is a header-only library. This means there is nothing to compile or link it to. Instead, as long as you have the header files in a standard location (/usr/local/include on *nix/Mac), then all you have to do is add that location to your preprocessor build step. Assuming that you are running *nix/Mac, and assuming that you have everything installed to the default locations (e.g. #include <Eigen/Core> references the file /usr/local/include/Eigen/Core), then a SUPER simple makefile would look like this: main: main.cpp g++ -I /usr/local/include main.cpp -o main Which says, in English: main depends on main.cpp to make main, use g++ to compile main.cpp, output file main, looking in the directory /usr/local/include for any headers it doesn't know about NOTE: there is a TAB in front of the g++ line, NOT four spaces. Hope that helps.
3,280,828
3,280,859
What does void(U::*)(void) mean?
I was looking at the implementation of the is_class template in Boost, and ran into some syntax I can't easily decipher. template <class U> static ::boost::type_traits::yes_type is_class_tester(void(U::*)(void)); template <class U> static ::boost::type_traits::no_type is_class_tester(...); How do I interpret void(U::*)(void) above? I'm familiar with C, so it appears somewhat analogous to void(*)(void), but I don't understand how U:: modifies the pointer. Can anyone help? Thanks
* indicates a pointer, because you can access its contents by writing *p. U::* indicates a pointer to a member of class U. You can access its contents by writing u.*p or pu->*p (where u is an instance of U). So, in your example, void (U::*)(void) is a pointer to a member of U that is a function taking no arguments and returning no value. Example: class C { void foo() {} }; typedef void (C::*c_func_ptr)(void); c_func_ptr myPointer = &C::foo;
3,280,864
3,280,900
Source IP from UDP packet in c under window OS
I want to get the source IP of UDP packet kindly guide me so that I can make it possible. I am working in c under windows platform.
Use the recvfrom function. It has a from parameter that points to a sockaddr structure that will receive the source address.
3,281,205
3,564,588
Using IMFSourceResolver::CreateObjectFromByteStream
I am trying to use the IMFSourceResolver::CreateObjectFromByteStream method to create a IMFMediaSource instance for a DRM protected WMA file. I am adapting the ProtectedPlayback sample from the Windows SDK as a playground. The end goal I wish to achieve is to have the playback process fed by a custom implementation if IMFByteStream that I will write. However, I cannot get either my simple IMFByteStream implementation or the implementations returned by the MFCreateFile function to work. Each returns a HRESULT of MF_E_UNSUPPORTED_BYTESTREAM_TYPE when passed to CreateObjectFromByteStream. I tested the sample project in its default state (using CreateObjectFromUrl on a file) with a DRM protected WMA file and it worked fine. The file is not corrupt and the license is valid. I don't understand why substituting this bit of code with CreateObjectFromByteStream( MFCreateFile() ) does not work. I have been able to find little documentation that covers using custom byte streams or what the resolver expects from a byte stream instance. If anybody has any experience with this stuff or any idea what I am doing wrong, some pointers would be appreciated. The code I am using is here: IMFByteStream* stream = NULL; HRESULT hr2 = MFCreateFile( MF_ACCESSMODE_READ, MF_OPENMODE_FAIL_IF_NOT_EXIST, MF_FILEFLAGS_NONE, L"C:\\IFB.wma", &stream); CHECK_HR(hr = pSourceResolver->CreateObjectFromByteStream( stream, NULL, MF_RESOLUTION_MEDIASOURCE, NULL, &ObjectType, &pSource)); I've not included the whole thing because its basically the same as the sample, I've only changed this part. Thanks, Steve
@pisomojado Thanks for the response, I totally forgot I had posted this question. The problem was, if I remember correctly, that CreateObjectFromByteStream needs a way to identify the content type. You can either do this by passing in a URL as well as the byte stream instance (pwszURL parameter) or by making the byte stream class implement IMFAttributes and handle the call to GetAllocatedString that asks for the content type. Since I was doing neither of these things, the resolver was just rejecting the stream. I would have thought that the resolver would attempt to recognize the stream content type via the first few bytes like you suggested in your answer, but for me it did not appear to do so. Not sure why this is, but nevermind. Steve
3,281,465
3,281,506
question about algorithm complexity
i have tried implement two methods recursive and dynamic method and both took 0 second it means that no one is better in my computer or something is wrong in code? here is these methods 1// recursive #include <stdio.h> #include <time.h> #include <iostream> using std::cout; void print(int n){ if (n<0) return ; cout<<n<<" "; print(n-1); } int main(){ int n=10; time_t start,end; double dif; time(&start); print(n); time(&end); dif=difftime(end,start); printf("it took you %.21f seconds ",dif); return 0; } 2.second method #include <iostream> #include <stdio.h> #include <time.h> using namespace std; void print (int n){ if (n<0) return ; while (n>=0){ cout<<n--<<endl; } } int main(){ int n=10; double dif; time_t start,end; time(&start); print(n); time(&end); dif=difftime(end,start); printf("it took you %.21f seconds",dif); return 0; }
A second clock resolution is not suitable for measuring such fast operations. I suggest you execute your code many times (something like 1 million times; use a for loop for this), estimate the overall time and then compute an average value. This way you'll get more reliable results. Just a quick note: I see you use cout in your functions. This is a bad idea: cout and usually most I/O operations are slow regarding to other operations. It is likely that your functions will spend most of their time to print the value, instead of computing it.
3,281,555
3,281,640
How do I convert QMap<QString, QMap<QString, int> > to a QVariant?
QVariant (needed for QSettings class) supports creation from QMap<QString, QVariant> But trying to initialise something like this: QMap<QString, QVariant(QMap<QString, QVariant>)> i; Gives the error: function returning a function. So then I tried the QMap<QString, QVariant> overload for QVariant() and got error: no matching function for call to QVariant::QVariant(QMap<QString, QMap<QString, int> >&) Now I tried a typecast: QMap<QString, (QVariant)QMap<QString, QVariant> > i; and got template argument 2 is invalid invalid type in declaration before ';' token So what's the required voodoo to convert a nested QMap to a QVariant object?
The error being reported is that QVariant(...) is not a type, but a function (c-tor). You should have just used: Map<QString, QVariant> i; and used QVariant(QMap<QString, QVariant>) only when assigning values to the map. The point is QVariant is anything really. So a map of QVariants, can have an int in one position (contained in the QVariant) and a QDate in another. So when declaring the type, you can't specify which types you want QVariant to hold.
3,281,659
3,281,717
Mixing post- and pre- increment/decrement operators on the same variable
Possible Duplicate: Why is ++i considered an l-value, but i++ is not? In C++ (and also in C), if I write: ++x-- ++(x--) i get the error: lvalue required as increment operand However (++x)-- compiles. I am confused.
Post- and pre-increment operators only work on lvalues. When you call ++i the value of i is incremented and then i is returned. In C++ the return value is the variable and is an lvalue. When you call i++ (or i--) the return value is the value of i before it was incremented. This is a copy of the old value and doesn't correspond to the variable i so it cannot be used as an lvalue. Anyway don't do this, even if it compiles.
3,281,666
3,281,673
What is "operator<<" called?
I know the names of most of the operators but not sure what operator<< and operator>> are called. i.e. operator=() // the assignment operator operator==() // the equality of comparison operator operator++() // the increment operator operator--() // decrement operator etc. operator<() // the less-than operator and so forth...
<< left shift >> right shift
3,281,925
3,281,953
What is default storage class for global variables?
What is default storage class of a global variable? While searching on web I found, some sites say it is static. But, static means internal linkage and the variable can not be available outside the file scope i.e it should not be available to other object files. But, they still can be accessed to other files using declarations like extern int i. And, if I explicitly mention static to global variable then it is not available outside the file scope. Then, what is correct default storage class for the global variables?
The default storage duration is static, but default linkage is external. You're not the only one to find it a bit confusing. The C Book (always a good reference) says: "You'll probably find the interactions between these various elements to be both complex and confusing: that's because they are!" The section with that quote, Declarations, Definitions and Accessibility, has a helpful table (8.1). The last row describes the case you're interested in. As it notes, data objects with no storage class specifier have external linkage and static duration.
3,281,984
3,282,632
Passing objects of different types with the same interface
I have a number of class, all with exactly the same interface. This interface defines a few methods, some of which are templated (the class itself may or may not be). So the interface looks something like this class MyClass { public: void Func1(); template <typename T> void Func2(T param); }; I have a number of functions which take various objects which conform to this interface but want to avoid having to know the exact implementation at compile time. Obviously, the default C++ solution would be to have a base type that all these classes derive from and pass around a pointer to that and have polymorphism do all the work. The problem is that templated member functions cannot be virtual so this method cannot be used. I also want to avoid changing the current set of classes that follow this interface because there are a large number of them, some of which are defined outside the scope of my project. The other solution is to template the functions that use these objects so they specialise for the right type. This could be a solution but due to legacy requirements templating a large number functions may not be possible (this is something I cannot do anything about as the client code isn't something I have responsibility for). My initial thought was to provide some kind of carrier class which is type neutral and in effects wraps the common interface here and has a base interface class to pass around the internal type. Something along the lines of class MyInterface { public: virtual void Func1() = 0; }; template <typename T> class MyImplementation { public: virtual void Func1() { m_impl->Func1(); } private: T* m_impl; }; But again the templated member functions seem to block this approach. I looked at the boost::any and boost::function classes which I thought might offer some kind of solution but they don't seem to give me the right answer. So, does anyone have any suggestions or work around on how to make this possible, if indeed it is? Personally I'm leaning towards having to template the various functions that require these objects - since that's the functionality templates provide - but thought it worth investigating first. Thanks in advance
What's not entirely clear to me is how you're resolving the parameter T to Func2, do you need some kind of dynamic dispatch on that too, or is it known at compile time at the call site? In the former case, it sounds like multimethods. In the latter, how about this variation on your interface idea: #include <iostream> template<class T> struct generic_delegate { virtual void call(T param) = 0; }; template<class U, class T> class fn_delegate : public generic_delegate<T> { U* obj; void (U::*fn)(T); public: fn_delegate(U* o, void (U::*f)(T)) : obj(o), fn(f) {} virtual void call(T param) { (obj->*fn)(param); } }; class A { public: template<class T> void fn(T param) { std::cout << "A: " << param << std::endl; } }; class B { public: template<class T> void fn(T param) { std::cout << "B: " << param << std::endl; } }; template<class T, class U> generic_delegate<T>* fn_deleg(U* o) { return new fn_delegate<U, T>(o, &U::template fn<T>); } int main() { A a; B b; generic_delegate<int>* i = fn_deleg<int>(&a); generic_delegate<int>* j = fn_deleg<int>(&b); i->call(4); j->call(5); } Obviously, the thing you'd be passing around are the generic delegate pointers.
3,282,133
3,282,175
Writing Unicode Characters to an OStream
I'm working with unicode/wide characters and I'm trying to create a toString method (Java ::toString equiv). Will ostream handle wide characters, if so is there a way to warn the consumer of the stream that it is unicode coming out of it?
Neither ostream nor the rest of C++ know anything about Unicode. Usually you write a string conversion in C++ as follows: template<typename Char, typename Traits> std::basic_ostream<Char, Traits>& operator<<(std::basic_ostream<Char, Traits>& stream, const YourType& object) { return stream << object.a << object.b; // or whatever } Whether you get something Unicode-like is up to the implementation. Streams in C++ are never text streams in the sense of Java, and C++'s strings are not strings in the sense of Java. If you want a real Unicode string, you might want to have a look at the ICU library.
3,282,608
3,282,638
Another C++ learning moment: returning strings from functions
I've got some basic questions about C++. Consider the following code in which I attempt to return a string. const std::string& NumberHolder::getValueString() { char valueCharArray[100]; sprintf_s(valueCharArray,"%f",_value); std::string valueString(valueCharArray); return valueString; } I'm attempting to return a string with the value of a class member called _value. However I'm getting the warning that I'm trying to pass back a pointer to a local variable. This is of course a bad thing. If I understand C++ enough at this point, this means that the pointer I pass back will already have delete called on it by the time someone tries to use it. So I modify: const std::string& NumberHolder::getValueString() { char valueCharArray[100]; sprintf_s(valueCharArray,"%f",_value); std::string valueString = new std::string(valueCharArray); return (*valueString); } This should create a pointer on the stack which will survive outside of this function. Two problems here though: 1) it doesn't compile anyway and I don't understand why (error = cannot convert from 'std::string *' to 'std::basic_string<_Elem,_Traits,_Ax>') and 2) This seems like a potential memory leak because I'm depending upon someone else to call delete on this guy. What pattern should I be using here?
You're defeating the point of having a std::string by allocating it on the heap! Just return it by value like this: std::string NumberHolder::getValueString() { char valueCharArray[100]; sprintf_s(valueCharArray,"%f",_value); return std::string(valueCharArray); } Just about every compiler nowadays will do return value optimization (RVO) on the return statement, so no copies should be made. Consider the following: NumberHolder holder; // ... std::string returnedString = holder.getValueString(); With RVO, the compiler will generate the code for the above implementation of NumberHolder::getValueString() such that std::string is constructed at the location of returnedString, so no copies are needed.
3,282,712
3,283,327
What is the equivalent type in C for REAL(KIND=real_normal) in Fortran?
I have a problem with passing of an array from Fortran to a c function: In the fortran the array is defined as REAL(KIND=real_normal) , DIMENSION(:), ALLOCATABLE :: array call cFunc(array) If define the cFunc as void cFunc(double *data){...} Than the data contains only "garbage" values. Where is the problem in this case? (with integers works this solution well). thx. EDIT: My platform: Compiler: VS 2008, Intel compiler 11 version OS: Win7 EDIT 2: I define the interface for the c-function like this (the code is reduced to one element, which makes problems, real function has more parameters): interface c_interface subroutine cFunc(array) bind (C, name = "cFunc") use iso_c_binding REAL(c_double), DIMENSION(*)::array end subroutine cFunc The memory in the fortran is allocated with ALLOCATE (array(numberOfElements)) call cFunc(array) At the moment i get an runtime error "Floating-point overflow". In some cases the array correct elements.
@High Performance Mark's suggestions are very good, and I highly recommend the ISO_C_Binding of Fortran 2003 (supported by numerous Fortran compilers) for interoperability between Fortran and C -- there is a larger issue here that makes the ISO_C_Binding more useful: Fortran allocatable arrays are more complicated then ordinary arrays. If you "hack it" and directly pass a pointer to the C code, you are likely to pass a pointer to a Fortran internal structure describing the allocatable array rather than a pointer to the sequence of numeric values. Allocatable arrays aren't directly supported by the ISO_C_Binding, but should work if you write an ISO_C_Binding interface (unlike what I wrote originally) -- the book "Fortran 95/2003 explained" says that the compiler will recognize the the called routine isn't receiving an allocatable array and will perform copy-in/copy-out to match the arrays. P.S. My guess is that copy-in/copy-out shouldn't be necessary for a simple allocatable actual argument. When the compiler recognizes via an explicit interface (which could be an ISO_C_Binding interface) that the dummy argument of the called routine is not an allocatable, the compiler should just be able to extract the pointer to the actual array from the description of the allocatable and pass that as the argument. Copy-in/copy out will be required in some cases, such as a pointer to a non-contiguous array, such as pointer with a non-unit stride (e.g., a pointer that points to elements 1, 3, 5, ...). But without any interface, the compiler will likely pass the descriptor of the allocatable array, which won't be what C is expecting....
3,282,728
3,282,744
Automatic locking/unlocking using scope in C++ (from C# background)
I've been using C# for the last few years and I am currently bug fixing in C++. In C# I could use lock on an object to make my code thread safe with: lock(lockObject) { // Do some work } This would unlock the lockOject if there was an exception within the // Do some work Is there something similar in C++? At the moment I can think of either: // Code { AutoLock lock(lockObject); // Do some work } // More Code But I don't like the curly braces just to scope my AutoLock. At the moment I'm doing: AutoLock lock(lockObject); // Do some work lock.Unlock(); And letting exception unwinding release the lock if there's an exception in //Do some work. What I'm doing at the moment works, but I'm wondering if there's a better way, thanks.
But I don't like the curly braces just to scope my AutoLock. That's how it's done in C++. Note that you don't need to have a separate scope block for each AutoLock; the following is fine too: { AutoLock lock1; AutoLock lock2; // more code goes here } // lock2 gets destroyed, then lock1 gets destroyed It doesn't have to be a separate scope block either; if you are locking something in a function and don't need it to be unlocked until the function returns, then you can simply use the function scope to constrain the lock . Likewise, if you are locking something during each iteration in a loop block, you can use the loop's scope block to constrain the lock. Your approach of manually unlocking the mutex when you are done with it is fine, but it's not idiomatic C++ and isn't as clear. It makes it harder to figure out where the mutex is unlocked (not much harder, perhaps, but harder than it needs to be).
3,282,885
3,282,906
Standard predicates for STL count_if
I'm using the STL function count_if to count all the positive values in a vector of doubles. For example my code is something like: vector<double> Array(1,1.0) Array.push_back(-1.0); Array.push_back(1.0); cout << count_if(Array.begin(), Array.end(), isPositive); where the function isPositive is defined as bool isPositive(double x) { return (x>0); } The following code would return 2. Is there a way of doing the above without writting my own function isPositive? Is there a built-in function I could use? Thanks!
std::count_if(v.begin(), v.end(), std::bind1st(std::less<double>(), 0)) is what you want. If you're already using namespace std, the clearer version reads count_if(v.begin(), v.end(), bind1st(less<double>(), 0)); All this stuff belongs to the <functional> header, alongside other standard predicates.
3,283,021
3,283,057
Compile a Standalone Static Executable
I'm trying to compile an executable (ELF file) that does not use a dynamic loader. I built a cross compiler that compiles mips from linux to be used on a simulator I made. I asserted the flag -static-libgcc on compilation of my hello.cpp file (hello world program). Apparently this is not enough though. Because there is still a segment in my executable which contains the name/path of the dynamic loader. What flags do I use to generate an executable which contains EVERYTHING needed to be run? Do I need to rebuild my cross compiler?
Try using the -static flag?
3,283,060
3,283,146
How do I run my code from the command line?
i have following code #include <iostream> using namespace std; int main(int argc,char arg[]){ int a=arg[1]; int b=arg[2]; int c=a+b; cout<<c<<endl; return 0; } i am using windows 7 microsoft visual c++ 2010 how run it from command line?
Navigate to the directory where the executable (.exe) is located. Then type the executable's name followed by two integer parameters. C:\TestProg\> TestProg 5 6 The problems in your original example are corrected here: #include <iostream> #include <sstream> int main(int argc, char *arg[]) { std::stringstream sa; std::stringstream sb; int a; int b; int c; if (argc >= 3) { // Convert string parameter into an integer. sa.str(arg[1]); sa >> a; if (!sa) { return 1; // error } // Convert string parameter into an integer. sb.str(arg[2]); sb >> b; if (!sb) { return 1; // error } } else { return 1; // error } c = a + b; std::cout << c << std::endl; return 0; }
3,283,562
3,283,832
Where on internet can we learn Secure Programming in c/c++
I am starting to learn everything about security and secure programming. I have always heard about things like buffer overflow vulnerability. But I don't know yet how such vulnerabilities are exploited. And how can we program securely enough to make sure that our code is robust. When I say all this, my programming languages of interest are c and c++. I am looking for free tutorials, and resources on internet where I can learn every ins-n-out of secure programming. Platform specific tips are also welcome. For example, I know that in Windows programming we can use functions like "memmove_s" to have secure code. But what are the equivalents in Linux/Unix? Or is it the same there? Should a c/c++ programmer worry about specially crafted formatted stings (like the very popular old PHP formatted strings vulverability)? A lot of questions here, but general idea is that I mean to learn Secure Programming. Thanks for every bit of help.
Check out CERT C Secure Coding Standard & CERT C++ Secure Coding Standard.
3,283,587
3,328,506
QWidget - resize animation
Say I have a QHBoxLayout where there are 2 QTextEdits and between them a button with an arrow to the right. When you click on the button, the right-side QTextEdit gradually closes by moving the left border until it meets the right one. Simultaneously, the right border of the left QTextEdit takes the place which the right QTextEdit released. And after pressing on the button, the state of the system is coming to the former one. EDIT: In order to organize this I have done the following: 1) In header file: class MyWidget : public QWidget { Q_OBJECT QTextEdit *m_textEditor1; QTextEdit *m_textEditor2; QPushButton *m_pushButton; QHBoxLayout *m_layout; int m_deltaX; public: MyWidget(QWidget * parent = 0); ~MyWidget(){} private slots: void closeOrOpenTextEdit2(bool isClosing); }; 2) In the source file: MyWidget::MyWidget(QWidget * parent):QWidget(parent),m_deltaX(0) { m_pushButton = new QPushButton(this); m_pushButton->setText(">"); m_pushButton->setCheckable(true); connect(m_pushButton, SIGNAL(clicked(bool)), this, SLOT(closeOrOpenTextEdit2(bool))); m_textEditor1 = new QTextEdit(this); m_textEditor1->setText("AAAAA AAAAAAAAAAA AAAAAAAAAAA AAAAAAA AAAAAAAAAAA AAAAAAAAAAA AA"); m_textEditor2 = new QTextEdit(this); m_layout = new QHBoxLayout; m_layout->addWidget(m_textEditor1); m_layout->addWidget(m_pushButton); m_layout->addWidget(m_textEditor2); setLayout(m_layout); } void MyWidget::closeOrOpenTextEdit2(bool isClosing) { QPropertyAnimation *animation1 = new QPropertyAnimation(m_textEditor2, "geometry"); QPropertyAnimation *animation2 = new QPropertyAnimation(m_pushButton, "geometry"); QPropertyAnimation *animation3 = new QPropertyAnimation(m_textEditor1, "geometry"); if(isClosing) //close the second textEdit { m_pushButton->setText("<"); QRect te2_1 = m_textEditor2->geometry(); m_deltaX = te2_1.width()-3; QRect te2_2(te2_1.x()+m_deltaX, te2_1.y(), 3 ,te2_1.height()); QRect pb_1 = m_pushButton->geometry(); QRect pb_2(pb_1.x()+m_deltaX, pb_1.y(), pb_1.width() ,pb_1.height()); QRect te1_1 = m_textEditor1->geometry(); QRect te1_2(te1_1.x(), te1_1.y(), te1_1.width()+m_deltaX, te1_1.height()); //animation->setDuration(10000); animation1->setStartValue(te2_1); animation1->setEndValue(te2_2); animation2->setStartValue(pb_1); animation2->setEndValue(pb_2); animation3->setStartValue(te1_1); animation3->setEndValue(te1_2); } else //open { m_pushButton->setText(">"); QRect te2_1 = m_textEditor2->geometry(); QRect te2_2(te2_1.x()-m_deltaX, te2_1.y(), 3+m_deltaX ,te2_1.height()); QRect pb_1 = m_pushButton->geometry(); QRect pb_2(pb_1.x()-m_deltaX, pb_1.y(), pb_1.width() ,pb_1.height()); QRect te1_1 = m_textEditor1->geometry(); QRect te1_2(te1_1.x(), te1_1.y(), te1_1.width()-m_deltaX, te1_1.height()); //animation->setDuration(10000); animation1->setStartValue(te2_1); animation1->setEndValue(te2_2); animation2->setStartValue(pb_1); animation2->setEndValue(pb_2); animation3->setStartValue(te1_1); animation3->setEndValue(te1_2); } animation1->start(); animation2->start(); animation3->start(); } EDIT: And I have the following problem: When I close the second QTextEdit (by clicking on the button) and resize the MyWidget, then the QTextEdit restores its state (but it should stay closed of course). How can I solve this problem? Please provide me with a code snippet.
Here what I wanted: Header file class MyWidget : public QWidget { Q_OBJECT QTextEdit *m_textEditor1; QTextEdit *m_textEditor2; QPushButton *m_pushButton; QHBoxLayout *m_layout; QVBoxLayout *m_buttonLayout; int m_deltaX; bool m_isClosed; public: MyWidget(QWidget * parent = 0); ~MyWidget(){} void resizeEvent( QResizeEvent * event ); private slots: void closeOrOpenTextEdit2(bool isClosing); }; Source file MyWidget::MyWidget(QWidget * parent):QWidget(parent),m_deltaX(0) { m_pushButton = new QPushButton(this); m_pushButton->setText(">"); m_pushButton->setCheckable(true); m_pushButton->setFixedSize(16,16); connect(m_pushButton, SIGNAL(clicked(bool)), this, SLOT(closeOrOpenTextEdit2(bool))); m_textEditor1 = new QTextEdit(this); m_textEditor1->setText("AAAAA AAAAAAAAAAA AAAAAAAAAAA AAAAAAA AAAAAAAAAAA AAAAAAAAAAA AA"); m_textEditor2 = new QTextEdit(this); m_buttonLayout = new QVBoxLayout(); m_buttonLayout->addWidget(m_pushButton); m_buttonLayout->addItem( new QSpacerItem(1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding) ); m_layout = new QHBoxLayout; m_layout->addWidget(m_textEditor1, 10); m_layout->addSpacing(15); m_layout->addLayout(m_buttonLayout); m_layout->setSpacing(0); m_layout->addWidget(m_textEditor2, 4); setLayout(m_layout); resize(800,500); } void MyWidget::closeOrOpenTextEdit2(bool isClosing) { m_isClosed = isClosing; QPropertyAnimation *animation1 = new QPropertyAnimation(m_textEditor2, "maximumWidth"); if(isClosing) //close the second textEdit { m_textEditor2->setMaximumWidth(m_textEditor2->width()); int textEdit2_start = m_textEditor2->maximumWidth(); m_deltaX = textEdit2_start; int textEdit2_end = 3; animation1->setDuration(500); animation1->setStartValue(textEdit2_start); animation1->setEndValue(textEdit2_end); m_pushButton->setText("<"); } else //open { int textEdit2_start = m_textEditor2->maximumWidth(); int textEdit2_end = m_deltaX; animation1->setDuration(500); animation1->setStartValue(textEdit2_start); animation1->setEndValue(textEdit2_end); m_pushButton->setText(">"); } animation1->start(); } void MyWidget::resizeEvent( QResizeEvent * event ) { if(!m_isClosed) m_textEditor2->setMaximumWidth( QWIDGETSIZE_MAX ); }
3,283,592
3,283,618
Is it not necessary to define a class member function?
The following code compiles and runs perfectly, #include <iostream> class sam { public: void func1(); int func2(); }; int main() { sam s; } Should it not produce a error for the lack of class member definition?
If you don't call the member functions, they don't have to be defined. Even if you call them, the compiler won't complain since they could be defined in some other compilation unit. Only the linker will complain. Not defining functions is accepted and common to force an error for undesired behavior (e.g. for preventing copying).
3,283,778
3,283,795
Why can I not push_back a unique_ptr into a vector?
What is wrong with this program? #include <memory> #include <vector> int main() { std::vector<std::unique_ptr<int>> vec; int x(1); std::unique_ptr<int> ptr2x(&x); vec.push_back(ptr2x); //This tiny command has a vicious error. return 0; } The error: In file included from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/mingw32/bits/c++allocator.h:34:0, from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/allocator.h:48, from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/memory:64, from main.cpp:6: c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h: In member function 'void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) [with _Tp = std::unique_ptr<int>, _Tp* = std::unique_ptr<int>*]': c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_vector.h:745:6: instantiated from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<int>, _Alloc = std::allocator<std::unique_ptr<int> >, value_type = std::unique_ptr<int>]' main.cpp:16:21: instantiated from here c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h:207:7: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::unique_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_Deleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> = std::unique_ptr<int>]' c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/ext/new_allocator.h:105:9: error: used here In file included from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/vector:69:0, from main.cpp:7: c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h: In member function 'void std::vector<_Tp, _Alloc>::_M_insert_aux(std::vector<_Tp, _Alloc>::iterator, _Args&& ...) [with _Args = {const std::unique_ptr<int>&}, _Tp = std::unique_ptr<int>, _Alloc = std::allocator<std::unique_ptr<int> >, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >, typename std::vector<_Tp, _Alloc>::_Base::_Tp_alloc_type::pointer = std::unique_ptr<int>*]': c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_vector.h:749:4: instantiated from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<int>, _Alloc = std::allocator<std::unique_ptr<int> >, value_type = std::unique_ptr<int>]' main.cpp:16:21: instantiated from here c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h:207:7: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::unique_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_Deleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> = std::unique_ptr<int>]' c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/vector.tcc:314:4: error: used here
You need to move the unique_ptr: vec.push_back(std::move(ptr2x)); unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it. Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object: std::unique_ptr<int> ptr(new int(1)); In C++14 we have an even better way to do so: make_unique<int>(5);
3,283,804
3,283,826
c++ get milliseconds since some date
I need some way in c++ to keep track of the number of milliseconds since program execution. And I need the precision to be in milliseconds. (In my googling, I've found lots of folks that said to include time.h and then multiply the output of time() by 1000 ... this won't work.)
See std::clock()