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
2,501,737
2,501,791
Why does std::cout convert volatile pointers to bool?
If you try to cout a pointer to a volatile type, even a volatile char pointer where you would normally expect cout to print the string, you will instead simply get '1' (assuming the pointer is not null I think). I assume output stream operator<< is template specialized for volatile pointers, but my question is, why? What use case motivates this behavior? Example code: #include <iostream> #include <cstring> int main() { char x[500]; std::strcpy(x, "Hello world"); int y; int *z = &y; std::cout << x << std::endl; std::cout << (char volatile*)x << std::endl; std::cout << z << std::endl; std::cout << (int volatile*)z << std::endl; return 0; } Output: Hello world 1 0x8046b6c 1
ostream::operator<< has the following overloads, among others: ostream& operator<< (bool val ); ostream& operator<< (const void* val ); When you pass in a volatile pointer, the second overload can't apply because volatile pointers cannot be converted to non-volatile without an explicit cast. However, any pointer can be converted to bool, so the first overload is chosen, and the result you see is 1 or 0. So the real reason for this is not an intentional decision on behalf of the standards committe, but simply that the standard does not specify an overload that takes a volatile pointer.
2,501,745
2,501,761
Exception Specification
I know that this feature will be deprecated in C++0x, but for me as a total novice it seems like a good idea to have it. Could anyone explain to me why isn't a good idea?
Please see this detailed article by Herb Sutter. He has the most thorough explanation of the problems and short comings of their design. A Pragmatic Look at Exception Specificiations http://www.gotw.ca/publications/mill22.htm
2,501,776
2,501,783
Inline functions in C++
If we define a member function inside the class definition itself, is it necessarily treated inline or is it just a request to the compiler which it can ignore.
Yes, functions that are defined inside a class body are implicitly inline. (As with other functions declared inline it doesn't mean that the complier has to perform inline expansion in places where the function is called, it just enables the permitted relaxations of the "one definition rule", combined with the requirement that a definition must be included in all translation units where the function is used.)
2,501,957
2,502,251
subtract one image from another using openCV
How can I subtract one image from another using openCV? Ps.: I coudn't use the python implementation because I'll have to do it in C++
Use LoadImage to load your images into memory, then use the Sub method. This link contains some example code, if that will help: http://permalink.gmane.org/gmane.comp.lib.opencv/36167
2,501,968
2,501,997
Visual C++ Enable Console
I created an Empty Project in Visual C++, but now I need the Console to display debug output. How can I enable the Console without recreating the project or show the output in the VS output window?
You can always call AllocConsole in code to create a console for your application, and attach it to the process. FreeConsole will remove the console, detaching the process from it, as well. If you want all standard output stream data to go to the console, you need to also use SetStdHandle to redirect the output appropriately. Here is a page showing working code to do this full process, including allocating the console and redirecting the output.
2,502,004
2,502,041
Undefined behavior on deleting char array trought void *
Is it true that the following yields undefined behavior: void * something = NULL; char * buffer = new char[10]; something = buffer; buffer = NULL; delete [] something; // undefined?? Do I first need to cast something to char * ?
Yes, strictly when you use delete[] the static type of the pointer that you delete[] must match the type of the array that you originally allocated or you get undefined behaviour. Typically, in many implementations, delete[] called on a void* which is actually an array of a type that has no non-trivial destructor works, but it's not guaranteed. delete[] buffer or delete[] (char*)something would both be valid.
2,502,203
2,502,297
Can boost::asio only receive full UDP datagrams?
I am working on a UDP server built with boost::asio and I started from the tutorial customizing to my needs. When I call socket.receive_from(boost::asio::buffer(buf), remote, 0, error); it fills my buffer with data from the packet, but, if my understanding is correct, it drops any data that won't fit in the buffer. Subsequent calls to receive_from will receive the next datagram available, so it looks to me like there is some loss of data without even a notice. Am I understanding this the wrong way? I tried reading over and over the boost::asio documentation, but I didn't manage to find clues as to how I am supposed to do this the right way. What I'd like to do is reading a certain amount of data so that I can process it; if reading an entire datagram is the only way, I can manage that, but then how can I be sure not to lose the data I am receiving? What buffer size should I use to be sure? Is there any way to tell that my buffer is too small and I'm losing information? I have to assume that I may be receiving huge datagrams by design.
This is not specific to boost; it's just how datagram sockets work. You have to specify the buffer size, and if the packet doesn't fit into the buffer, then it will be truncated and there is no way to recover the lost information. For example, the SNMP protocol specifies that: An implementation of this protocol need not accept messages whose length exceeds 484 octets. However, it is recommended that implementations support larger datagrams whenever feasible. In short: you have to take it into account when designing your communication protocol that datagrams may be lost, or they may be truncated beyond some specified size.
2,502,232
2,502,263
Which programming languages support constant methods?
Which programming languages other than C++ support the concept of a constant class method? That is, what languages allow the programmer to constrain a method in such a way that it is guaranteed not to change the state of an object to which the method is applied? Please provide examples or references in your answer.
Haskell, since it's purely functional. Actually, every value/method is constant in Haskell even though mutable state/IO can be modelled through a mathematical construct called monad.
2,502,262
2,502,368
Profiling shared library/plugins written in C++ for Python?
I've got a C++ library that lets me write plugins in C++ and then automatically exposes them to python. I'm working on some networking stuff in a plugin and I'd like to profile it with something like gprof, but simply compiling with -pg and running the plugin via python doesn't generated the necessary profiling data. Unfortunately the plugins are tightly coupled so it's not possible to run them as standalone programs. Does anyone know of ways to profile shared libraries and/or plugins independently of the program running them?
I've found valgrind's cachegrind with KCachegrind to be helpful in analysis of un-prepared (e.g. no gprof code embedded) binaries.
2,502,314
2,502,350
Setting an std::string variable value from gdb?
Is it possible... when the debugger is stopped at a breakpoint, to modify the value of a std::string variable without resorting to hacks like tweaking the memory image of the current buffer? e.g. something like "set var mystring="hello world" ?
Try this (tested and works for me): call mystring.assign("hello world") The key is that instead of modifying memory directly, you call the object's functions to change its state. It so happens that std::basic_string has a member function called assign which does the job.
2,502,394
2,502,454
The cost of passing by shared_ptr
I use std::tr1::shared_ptr extensively throughout my application. This includes passing objects in as function arguments. Consider the following: class Dataset {...} void f( shared_ptr< Dataset const > pds ) {...} void g( shared_ptr< Dataset const > pds ) {...} ... While passing a dataset object around via shared_ptr guarantees its existence inside f and g, the functions may be called millions of times, which causes a lot of shared_ptr objects being created and destroyed. Here's a snippet of the flat gprof profile from a recent run: Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls s/call s/call name 9.74 295.39 35.12 2451177304 0.00 0.00 std::tr1::__shared_count::__shared_count(std::tr1::__shared_count const&) 8.03 324.34 28.95 2451252116 0.00 0.00 std::tr1::__shared_count::~__shared_count() So, ~17% of the runtime was spent on reference counting with shared_ptr objects. Is this normal? A large portion of my application is single-threaded and I was thinking about re-writing some of the functions as void f( const Dataset& ds ) {...} and replacing the calls shared_ptr< Dataset > pds( new Dataset(...) ); f( pds ); with f( *pds ); in places where I know for sure the object will not get destroyed while the flow of the program is inside f(). But before I run off to change a bunch of function signatures / calls, I wanted to know what the typical performance hit of passing by shared_ptr was. Seems like shared_ptr should not be used for functions that get called very often. Any input would be appreciated. Thanks for reading. -Artem Update: After changing a handful of functions to accept const Dataset&, the new profile looks like this: Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls s/call s/call name 0.15 241.62 0.37 24981902 0.00 0.00 std::tr1::__shared_count::~__shared_count() 0.12 241.91 0.30 28342376 0.00 0.00 std::tr1::__shared_count::__shared_count(std::tr1::__shared_count const&) I'm a little puzzled by the number of destructor calls being smaller than the number of copy constructor calls, but overall I'm very pleased with the decrease in the associated run-time. Thanks to all for their advice.
Always pass your shared_ptr by const reference: void f(const shared_ptr<Dataset const>& pds) {...} void g(const shared_ptr<Dataset const>& pds) {...} Edit: Regarding the safety issues mentioned by others: When using shared_ptr heavily throughout an application, passing by value will take up a tremendous amount of time (I've seen it go 50+%). Use const T& instead of const shared_ptr<T const>& when the argument shall not be null. Using const shared_ptr<T const>& is safer than const T* when performance is an issue.
2,502,922
2,503,023
Preventing objects from being linked if they are not needed?
I have an ARM project that I'm building with make. I'm creating the list of object files to link based on the names of all of the .c and .cpp files in my source directory. However, I would like to exclude objects from being linked if they are never used. Will the linker exclude these objects from the .elf file automatically even if I include them in the list of objects to link? If not, is there a way to generate a list of only the objects that need to be linked?
If you are using RealView, it seems that it is possible. This section discusses it: 3.3.3 Unused section elimination Unused section elimination removes code that is never executed, or data that is not referred to by the code, from the final image. This optimization can be controlled by the --remove, --no_remove, --first, --last, and --keep linker options. Use the --info unused linker option to instruct the linker to generate a list of the unused sections that have been eliminated.
2,503,024
2,503,046
How does one create a shared_ptr to pass to a function that takes a void *
That's pretty much it. I need to allocate memory and pass it to a function that takes a void *. I'd like to use a shared_ptr but I don't know how to do it.
Do you mean something like: boost::shared_ptr<int> myInt(new int(5)); call_some_function(myInt.get()); This only let's the function use the int*. It shouldn't try to delete it or take ownership. If you want just raw memory, use a vector: std::vector<char> memory(blockSize); call_some_function(&blockSize[0]); Again, the memory belongs to the vector. If your function does want ownership, there's no need to wrap it into something, since you won't be managing it: call_some_function(new int); call_some_function(new char[blockSize]); Make sure the function will be releasing it with a call to delete/delete[]. If not (for example, it intends to use free()), you'll need to use malloc instead: template <typename T> T* malloc_new(void) { void* memory = std::malloc(sizeof(T)); if (!memory) throw std::bad_alloc(); try { return new (memory) T(); } catch(...) { std::free(memory); throw; } } call_some_function(malloc_new<int>()); call_some_function(malloc(blockSize));
2,503,055
2,503,080
What is the best place to find software development conference listings?
I am interested in an array of software ideas and use more than one language, is there somewhere that concisely lists software development conferences year by year? I'd like to know what options are out there for this year and searching by ideology/language isn't practical in my opinion to get an overall. Some ideologies/languages that interest me (but open to others): TDD (with various languages, not just Java) Agile (w/Scrum, Kanban) Java C++ .NET/C# Development Tools (IDE, Debuggers, etc...)
Not a listing but I use http://www.infoq.com/ to watch videos of past conferences.
2,503,103
2,503,180
What's the problem with the code below?
#include <iostream> #include <vector> using namespace std; int main(void) { int i, s, g; vector<int> a; cin >> s; for(i=1;i<=s;i++) { g = s; if(g<10) a.push_back(g); else { vector<int> temp; while(g > 0) { int k = g % 10; g = g / 10; temp.push_back(g); } for(int j=temp.size();j>0;j--) { a.push_back(temp[j]); } } } cout << a[s-1] << endl; return 0; } What is wrong with the code above ? It doesn't give me the appropriate results. The vector a is supposed to hold the values from 1, 2, 3...up to s such that a = 12345..910111213... and print to output a[s]. Ex if s=15 a=123456789101112131415 and a[15] = 2 . If someone could tell me what's the problem
Corrected code: int i, s, g; vector<int> a; cin >> s; for(i=1;i<=s;i++) { g = i; //Why was it s? if(g<10) a.push_back(g); else { vector<int> temp; while(g > 0) { int k = g % 10; g = g / 10; temp.push_back(k); //You need to push the remainder } for(int j=temp.size()-1;j>=0;j--) //Out of bounds error { a.push_back(temp[j]); } } } cout << a[s-1] << endl; return 0; And a looks like this when s = 15 - is this what you were looking for? a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5 a[5] = 6 a[6] = 7 a[7] = 8 a[8] = 9 a[9] = 1 a[10] = 0 a[11] = 1 a[12] = 1 a[13] = 1 a[14] = 2 a[15] = 1 a[16] = 3 a[17] = 1 a[18] = 4 a[19] = 1 a[20] = 5
2,503,222
2,503,500
Convert a code from FORTRAN to C
I have the following FORTRAN code which I need to convert to C or C++. I already tried using f2c, but it didn't work out. It has something to do with conversion from Lambert Conformal wind vector to a True-North oriented vector. Is anyone experienced in FORTRAN who could possibly help? PARAMETER ( ROTCON_P = 0.422618 ) PARAMETER ( LON_XX_P = -95.0 ) PARAMETER ( LAT_TAN_P = 25.0 ) do j=1,ny_p do i=1,nx_p angle2 = rotcon_p*(olon(i,j)-lon_xx_p)*0.017453 sinx2 = sin(angle2) cosx2 = cos(angle2) do k=1,nzp_p ut = u(i,j,k) vt = v(i,j,k) un(i,j,k) = cosx2*ut+sinx2*vt vn(i,j,k) =-sinx2*ut+cosx2*vt end if end do end do Thanks a lot for any help or tip.
I speak Fortran as well as Tarzan speaks English, but this should be the gist of it in C: #include <math.h> const double ROTCON_P = 0.422618; const double LON_XX_P = -95.0; const double LAT_TAN_P = 25.0; int i, j, k; double angle2, sinx2, cosx2, ut, vt; double un[nzp_p][ny_p][nx_p]; double vn[nzp_p][ny_p][nx_p]; for (j=0; j<ny_p; ++j) { for (i=0; i<nx_p; ++i) { angle2 = ROTCON_P * (olon[j][i] - LON_XX_P) * 0.017453; sinx2 = sin(angle2); cosx2 = cos(angle2); for (k=0; k<nzp_p; ++k) { ut = u[k][j][i]; vt = v[k][j][i]; un[k][j][i] = (cosx2 * ut) + (sinx2 * vt); vn[k][j][i] = (-1 * sinx2 * ut) + (cosx2 * vt); } } } You will need to declare olon, u, v, nx_p, ny_p, and nzp_p somewhere and assign them a value before running this code. There is not enough context info given for me to know exactly what they are.
2,503,269
2,503,303
Is this an acceptable use of "ASCII arithmetic"?
I've got a string value of the form 10123X123456 where 10 is the year, 123 is the day number within the year, and the rest is unique system-generated stuff. Under certain circumstances, I need to add 400 to the day number, so that the number above, for example, would become 10523X123456. My first idea was to substring those three characters, convert them to an integer, add 400 to it, convert them back to a string and then call replace on the original string. That works. But then it occurred to me that the only character I actually need to change is the third one, and that the original value would always be 0-3, so there would never be any "carrying" problems. It further occurred to me that the ASCII code points for the numbers are consecutive, so adding the number 4 to the character "0", for example, would result in "4", and so forth. So that's what I ended up doing. My question is, is there any reason that won't always work? I generally avoid "ASCII arithmetic" on the grounds that it's not cross-platform or internationalization friendly. But it seems reasonable to assume that the code points for numbers will always be sequential, i.e., "4" will always be 1 more than "3". Anybody see any problem with this reasoning? Here's the code. string input = "10123X123456"; input[2] += 4; //Output should be 10523X123456
From the C++ standard, section 2.2.3: In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous. So yes, if you're guaranteed to never need a carry, you're good to go.
2,503,331
2,503,360
undefined reference linker error
I've stuck myself in a c++ project under linux ,for which I get an undefined reference when I try to create an object of a class that I just wrote.I believe this is an linker error caused by the fact that somewhere , somehow I should tell the linker to take into account the new class. I looked at the project properties and at the run command it executes a script (cmake.sh) . Because the project wasn't created by me , and because I'm a novice in working under linux, I just don't know how to direct the linker to do what I expect him to do !
Is your new source file included in the makefile for the project you're working on? (I'm guessing it's a makefile based on the shell script being names cmake.sh. If the script isn't using make, then the project description file will have a different name....)
2,503,533
2,503,542
How can I declare classes that refer to each other?
It's been a long time since I've done C++ and I'm running into some trouble with classes referencing each other. Right now I have something like: a.h class a { public: a(); bool skeletonfunc(b temp); }; b.h class b { public: b(); bool skeletonfunc(a temp); }; Since each one needs a reference to the other, I've found I can't do a #include of each other at the top or I end up in a weird loop of sorts with the includes. So how can I make it so that a can use b and vice versa without making a cyclical #include problem? thanks!
You have to use Forward Declaration: a.h class b; class a { public: a(); bool skeletonfunc(b temp); } However, in many situations, this can force you to work with references or pointers in your method calls or member variables, since you can't have the full types in both class headers. If the size of the type must be known, you need to use a reference or pointer. You can, however, use the type if only a method declaration is required.
2,503,585
2,504,952
How is it possible to legally write ::: in C++ and ??? in C#?
These questions are a kind of game, and I did not find the solution for them. It is possible to write ::: in C++ without using quotes or anything like this and the compiler will accept it (macros are prohibited too). And the same is true for C# too, but in C#, you have to write ???. I think C++ will use the :: scope operator and C# will use ? : , but I do not know the answers to them. Any idea?
You can write three consecutive question marks in C# without quotes, but not without whitespace, using the null-coalescing operator and the nullable alias character: object x = 0; int y = x as int? ?? 1;
2,503,807
2,503,845
Declaring an enum within a class
In the following code snippet, the Color enum is declared within the Car class in order to limit the scope of the enum and to try not to "pollute" the global namespace. class Car { public: enum Color { RED, BLUE, WHITE }; void SetColor( Car::Color color ) { _color = color; } Car::Color GetColor() const { return _color; } private: Car::Color _color; }; (1) Is this a good way to limit the scope of the Color enum? Or, should I declare it outside of the Car class, but possibly within its own namespace or struct? I just came across this article today, which advocates the latter and discusses some nice points about enums: http://gamesfromwithin.com/stupid-c-tricks-2-better-enums. (2) In this example, when working within the class, is it best to code the enum as Car::Color, or would just Color suffice? (I assume the former is better, just in case there is another Color enum declared in the global namespace. That way, at least, we are explicit about the enum to we are referring.)
If Color is something that is specific to just Cars then that is the way you would limit its scope. If you are going to have another Color enum that other classes use then you might as well make it global (or at least outside Car). It makes no difference. If there is a global one then the local one is still used anyway as it is closer to the current scope. Note that if you define those function outside of the class definition then you'll need to explicitly specify Car::Color in the function's interface.
2,503,939
2,504,044
How to create a array of boost matrices?
How can I define a array of boost matrices as a member variable? None of the following worked. boost::numeric::ublas::matrix<double> arrayM(1, 3)[arraySize]; boost::numeric::ublas::matrix<double>(1, 3) arrayM[arraySize]; boost::numeric::ublas::matrix<double> arrayM[arraySize](1, 3); Thanks, Ravi.
The size you initialize it with has nothing to do with the type. Therefore: // this makes things easier! typedef boost::numeric::ublas::matrix<double> matrix_type; // this is the type (no initialization) matrix_type arrayM[arraySize]; The problem comes with initializing the array. You can't do this: TheClass::TheClass() : arrayM(1, 3) // nope {} Instead, you have to let them default-construct, then resize them all: TheClass::TheClass() { std::fill(arrayM, arrayM + arraySize, matrix_type(1, 3)); } Since you're using boost, consider using boost::array, since it gives a nicer syntax: typedef boost::numeric::ublas::matrix<double> matrix_type; typedef boost::array<matrix_type, arraySize> matrix_array; matrix_array arrayM; // ah TheClass::TheClass() { arrayM.assign(matrix_type(1, 3)); }
2,504,161
2,504,852
Possible: Set Operations on Disparate Maps with Same Key Type?
Let's say I have two maps: typedef int Id; std::map<Id, std::string> idToStringMap; std::map<Id, double> idToDoubleMap; And let's say I would like to do a set operation on the keys of the two maps. Is there an easier way to do this than to create a custom "inserter" iterator? such that I could do something like: std::set<Id> resultSet; set_difference( idToStringMap.begin(), idToStringMap.end(), idToDoubleMap.begin(), idToDoubleMap.end(), resultSet.begin() ); My experimentation results imply that it will be necessary to create a custom inserter and perhaps a custom key comparer to do this, but I want for some insight/shortcut before doing so.
My solution using iain's advice: template <typename T> class Select1st : public std::unary_function<T&,typename T::first_type> { public: int operator() (T & value) const { return value.first; } }; template <typename T> class KeyGrabItorAdapter : public boost::transform_iterator< Select1st<typename T::value_type>, typename T::iterator > { public: KeyGrabItorAdapter( typename T::iterator itor ) : boost::transform_iterator<Select1st<typename T::value_type>, typename T::iterator> ( itor, Select1st<typename T::value_type>() ) { } }; having the preceeding allows the following: typedef std::map<int, int> IntToIntMap; IntToIntMap intToIntMapA; IntToIntMap intToIntMapB; typedef std::map<int, double> IntToDoubleMap; IntToDoubleMap intToDoubleMapA; IntToDoubleMap intToDoubleMapB; KeyGrabItorAdapter<IntToIntMap> grabFirstABegin( intToIntMapA.begin() ) ; KeyGrabItorAdapter<IntToIntMap> grabFirstAEnd( intToIntMapA.end() ) ; KeyGrabItorAdapter<IntToDoubleMap> grabFirstBBegin( intToDoubleMapB.begin() ) ; KeyGrabItorAdapter<IntToDoubleMap> grabFirstBEnd( intToDoubleMapB.end() ) ; std::set<int> intResultSet; set_difference( grabFirstABegin, grabFirstAEnd, grabFirstBBegin, grabFirstBEnd, inserter( intResultSet, intResultSet.begin()), intToIntMapA.key_comp() );
2,504,181
2,504,224
quiz ; does this compile and if so what does it return (I know the answer)
I found this typo recently: if (name.find('/' != string::npos)) Obviously the dev meant to type if(name.find('/') != string::npos) But I was amazed that to find that the error even compiles with -Wall -Werror (didnt try with -pedantic) So, coffee quiz: does it evaluate to true or false?
'/' doesn't equal string::npos since npos is required to be negative, and none of the characters in the basic execution character set is allowed to be negative. Therefore, it's going to look for a value of 1 in the string (presumably a string anyway) represented by name. That's a pretty unusual value to have in a string, so it's usually not going to find it, which means it'll return std::string::npos, which will convert to true. Edit: as Johannes pointed out, although the value assigned to npos must be negative 1 (as per 21.3/6) that's being assigned to a size_type, which must be unsigned, so the result won't be negative. This wouldn't normally make any real difference though -- the '/' would be compared to npos using unsigned arithmetic, so the only way they could have the same value would be if 1) '/' was encoded as -1 (not allowed as above) or char had the same range as size_type. In theory, the standard allows char to have the same range as other integral types. In fact, quite a bit of I/O depends on EOF having a value that couldn't originate from the file, which basically translates to a requirement that char have a range that's smaller than int, not just smaller than or equal to (as the standard directly requires). That does leave one loophole, though it's one that would generally be quite horrible: that char and short have the same range, size_type is the same as unsigned short, and int has a greater range than char/short. Giving char and short the same range wouldn't be all that horrible, but restricting size_type to the same range as short normally would be -- in a typical case, short is 16 bits, so it would restrict containers to 64K. That kind of restriction was problematic 20 years ago under MS-DOS; it simply wouldn't be accepted in most markets today.
2,504,253
2,516,231
C++ tool to generate random XML files from XML Schema?
I think there should be a tool to do so ? is anyone here aware of any ? I saw other posts related to this but found none for C++, I am aware that I can do that with JAVA and C#.
If you use XML Spy or oXygen, you can generate sample XML files based on a schema. Both tools accept commandline options and can be run in batch mode so that'll probably fit in your unit tests, if that's what you're after. Wrap your own C++ code around it and you're in business. If you need quality XML, with tons of tweakable options, you might want to check out http://www.code-generator.com/XML-Sample-Generator.aspx. No C++ here, just a tool that works, and rises beyond the default "lorem ipsum..." output. HTH, ~Rob
2,504,496
2,504,508
What does "error: invalid function declaration" mean?
With GCC 4.1.2, I get the error tmp.cpp:8: error: invalid function declaration for the following code namespace edit { class A { public: void foo( ); }; } void edit:A::foo( ) { }
The problem was easy to fix: void edit:A::foo( ) { ^ missing ':' should be: void edit::A::foo( ) {
2,504,536
21,629,914
Why allow concatenation of string literals?
I was recently bitten by a subtle bug. char ** int2str = { "zero", // 0 "one", // 1 "two" // 2 "three",// 3 nullptr }; assert( int2str[1] == std::string("one") ); // passes assert( int2str[2] == std::string("two") ); // fails If you have godlike code review powers you'll notice I forgot the , after "two". After the considerable effort to find that bug I've got to ask why would anyone ever want this behavior? I can see how this might be useful for macro magic, but then why is this a "feature" in a modern language like python? Have you ever used string literal concatenation in production code?
I see several C and C++ answers but none of the really answer why or really what was the rationale for this feature? In C++ this is feature comes from C99 and we can find the rationale for this feature by going to Rationale for International Standard—Programming Languages—C section 6.4.5 String literals which says (emphasis mine): A string can be continued across multiple lines by using the backslash–newline line continuation, but this requires that the continuation of the string start in the first position of the next line. To permit more flexible layout, and to solve some preprocessing problems (see §6.10.3), the C89 Committee introduced string literal concatenation. Two string literals in a row are pasted together, with no null character in the middle, to make one combined string literal. This addition to the C language allows a programmer to extend a string literal beyond the end of a physical line without having to use the backslash–newline mechanism and thereby destroying the indentation scheme of the program. An explicit concatenation operator was not introduced because the concatenation is a lexical construct rather than a run-time operation. Python which seems to have the same reason, this reduces the need for ugly \ to continue long string literals. Which is covered in section 2.4.2 String literal concatenation of the The Python Language Reference.
2,504,562
2,504,572
Is it safe to define _HAS_TRADITIONAL_STL to enable STL functionality?
In attempting to use std::select1st from <functional> in a VS2008 project I found that it was ifdef'd out by a _HAS_TRADITIONAL_STL guard. Is there a reason for this? Is it safe to simply define _HAS_TRADITIONAL_STL before including <functional>?
The reason std::select1st is not present by default is that it is not part of the C++ standard library. It is one of the parts of the Standard Template Library (STL) that was not adopted into the C++ standard. I can't find any documentation on MSDN for _HAS_TRADITIONAL_STL, and it doesn't appear to be used in the version of the standard library distributed with Visual Studio 2010. It is probably included in the library by Dinkumware when they deliver it to Microsoft. That having been said, it is probably safe to define if you want to use std::select1st. Just note that using anything enabled by that flag is implementation-specific and nonportable (and may even change between versions of Visual C++). You would probably be better off implementing your own select1st function: template <typename PairT> struct select1st : public std::unary_function<PairT, typename PairT::first_type> { typename PairT::first_type operator()(const PairT& a) { return a.first; } };
2,504,814
2,504,876
How to launch a mac application without a terminal window
I've written an open-source c++ application and it works fine on Windows and Linux, I finally got a Mac Mini (with 10.5.8) so I've just been testing the Mac version. My application works fine when running it from inside a terminal window and typing ./appname , but if instead I double click on it from the finder, then it opens a termnial window first and then runs my app but it doesn't seem to set the working directory to the correct location so my app dies. How do I make my app so when it launches by being double clicked on it doesn't open a terminal window first and how can I have the current directory set to the apps location automatically?
Mac binaries are set to be opened with the 'Terminal' program; there's no way around that, except by making a full application package, or have another program launch it via system or something like that. When double-clicking on a binary, the terminal window opens with ~ as the current directory. I suggest you use chdir(2) in your program to ensure it is running in the right directory if you need it in the first place.
2,504,825
2,505,012
Why does a multilanguage solution not work?
My solution has a C# application project C# User Controls project C++ Mathematics project One of the UserControls uses function from the Mathematics (C++ project). This UserControl is used in the application. Building and starting the application works just fine. When typing the IntelliSense suggests all the contained classes and methods. The UserControl appears correctly, but on clicking a button which calls the C++ function I get a BadImageFormatException (it pops out on the end of the automatically created Main function). The help suggests to use /fixed:no for linking, but that is already set up.
You can get BadImageFormatException when running a 32bit dll on a 64bit system. Try setting the target to "x86" on all your projects.
2,505,042
2,511,526
How to parse a tar file in C++
What I want to do is download a .tar file with multiple directories with 2 files each. The problem is I can't find a way to read the tar file without actually extracting the files (using tar). The perfect solution would be something like: #include <easytar> Tarfile tar("somefile.tar"); std::string currentFile, currentFileName; for(int i=0; i<tar.size(); i++){ file = tar.getFileText(i); currentFileName = tar.getFileName(i); // do stuff with it } I'm probably going to have to write this myself, but any ideas would be appreciated..
I figured this out myself after a bit of work. The tar file spec actually tells you everything you need to know. First off, every file starts with a 512 byte header, so you can represent it with a char[512] or a char* pointing at somewhere in your larger char array (if you have the entire file loaded into one array for example). The header looks like this: location size field 0 100 File name 100 8 File mode 108 8 Owner's numeric user ID 116 8 Group's numeric user ID 124 12 File size in bytes 136 12 Last modification time in numeric Unix time format 148 8 Checksum for header block 156 1 Link indicator (file type) 157 100 Name of linked file So if you want the file name, you grab it right here with string filename(buffer[0], 100);. The file name is null padded, so you could do a check to make sure there's at least one null and then leave off the size if you want to save space. Now we want to know if it's a file or a folder. The "link indicator" field has this information, so: // Note that we're comparing to ascii numbers, not ints switch(buffer[156]){ case '0': // intentionally dropping through case '\0': // normal file break; case '1': // hard link break; case '2': // symbolic link break; case '3': // device file/special file break; case '4': // block device break; case '5': // directory break; case '6': // named pipe break; } At this point, we already have all of the information we need about directories, but we need one more thing from normal files: the actual file contents. The length of the file can be stored in two different ways, either as a 0-or-space-padded null-terminated octal string, or "a base-256 coding that is indicated by setting the high-order bit of the leftmost byte of a numeric field". Numeric values are encoded in octal numbers using ASCII digits, with leading zeroes. For historical reasons, a final NUL or space character should be used. Thus although there are 12 bytes reserved for storing the file size, only 11 octal digits can be stored. This gives a maximum file size of 8 gigabytes on archived files. To overcome this limitation, star in 2001 introduced a base-256 coding that is indicated by setting the high-order bit of the leftmost byte of a numeric field. GNU-tar and BSD-tar followed this idea. Additionally, versions of tar from before the first POSIX standard from 1988 pad the values with spaces instead of zeroes. Here's how you would read the octal format, but I haven't written code for the base-256 version: // in one function int size_of_file = octal_string_to_int(&buffer[124], 11); // elsewhere int octal_string_to_int(char *current_char, unsigned int size){ unsigned int output = 0; while(size > 0){ output = output * 8 + *current_char - '0'; current_char++; size--; } return output; } Ok, so now we have everything except the actual file contents. All we have to do is grab the next size bytes of data from the tar file and we'll have our file contents: // Get to the next block after the header ends location += 512; file_contents = new char[size]; memcpy(file_contents, &buffer[location], size); // Go to the next block by rounding up to 512 // This isn't necessarily the most efficient way to do this, // but it's the most obvious. location += (int)ceil(size / 512.0)
2,505,108
2,509,063
Error LNK1223 on ARM builds
eMbedded Visual C++ 3 project, that is building for PocketPC 2000. On the ARM build, the linker throws the following error: fatal error LNK1223: invalid or corrupt file: file contains invalid pdata contributions On SH3, the project compiles, links, and works. The project also works when built for ARM on Visual C++ 2005, but I need to test builds specifically from eVC3. Any ideas, please? What's a pdata contribution and how do I affect (or disable) those? It's something to do with exception handling; I've tried disabling SEH by specifying /EHsc, to no effect.
Very weird. I tried commenting out everything in the file. The error went away when I commented out a function that was extern "C" void __declspec(naked) with no body (body #ifdef'fed away). I have similar functions in the project, but they did not throw any errors like this. Maybe a compiler bug...
2,505,240
2,505,247
Usage of std::string.append causes "Stack around the variable 'result' was corrupted"
I have the following code : std::string Utils::get() { std::string result; result.append(1, 'x'); result.append(1, 'x'); result.append(1, 'x'); return result; } I expect 'xxx' to be returned. However, when I run under debug mode, I get the warning "Stack around the variable 'result' was corrupted" Am I using append function the wrong way?
Your use of append is correct. Something else (possibly just before calling the function, etc.) is corrupting the stack. It's only when you use the stack some more (a function call in this case) will it detect it. The reason you won't see it in Release is because the function call is (likely) inlined. Ergo, the stack isn't manipulated like it is now, and the result is different. Post some more context and we'll help you track it down.
2,505,257
2,505,263
Manage bad_alloc exception in C++ construtor
I have Java experience and recently am doing some C++ coding. My question is that if I have class A, in which I have to instantiate class B and class C as two of the member variables of A. If in the constructor of A, should I assume that allocations of class B and C never fail, and handle the bad allocation exception in the destructor of A? If I don't make that assumption, meaning that I add some try catch block to catch bad_alloc of class B and class C, then if the allocation exception occurs, should I do clean up in the constructor of A? What are the recommended practices? If "new" generates a bad allocation, what value does the pointer carry?
If an exception is thrown during the construction of A, your destructor will not be called. Obviously the solution depends on what you're doing, but ideally you won't have to do any cleaning up. You should utilize RAII, and your class members should clean-up themselves. That is, don't use any pointers raw; wrap them up and let the wrapper take care of it. Surprise! C++ programmers hate memory management just like you. We like to wrap it up and forget about it. If you truly need to, though, I think this is common: struct foo { int* i; some_member_that_could_throw crap; foo() // do *not* new i! if the second member throws, memory is leaked. { // rather: // okay we made it, the other member must have initialized i = new int; } }; Concerning your pointer, it's value remains unchanged. When new throws an exception (for whatever reason), the stack is unwound. The rest of the expression is abandoned. Here's how exceptions and object creation will work. It's a recursive process, because each member or base class will in turn follow this list. Fundamental types have no constructors; this is the base case for the recursion. First, construct each of our base classes. (Which in turn run this list.) Initialize members of the class, one by one. Run the constructor body. finish with a fully constructed object. Obviously, if item 1 fails there isn't any cleaning up for us to do, as none of our members have been initialized. We're good there. Two is different. If at any point one of those fails to construct , the initialized members so far will be destructed, then the constructor will stop progress and the exception goes on it's merry way. This is why when you let your members clean up after themselves you have nothing to worry about. The uninitialized have nothing to do, and the initialized are going to have their destructors run, where cleanup occurs. Three even more so. now that your objects are fully initialized, you're guaranteed they will all have their destructors run. Again, wrap things up and you have nothing to worry about. However if you have a raw pointer lying around, this is the time for a try/catch block: try { // some code } catch (..) // catch whatever { delete myrawPointer; // stop the leak! throw; // and let the exception continue } It's much messier to write exception-safe code without RAII.
2,505,328
2,505,410
Calling class method through NULL class pointer
I have following code snippet: class ABC{ public: int a; void print(){cout<<"hello"<<endl;} }; int main(){ ABC *ptr = NULL: ptr->print(); return 0; } It runs successfully. Can someone explain it?
Under the hood most compilers will transform your class to something like this: struct _ABC_data{ int a ; }; // table of member functions void _ABC_print( _ABC_data* this ); where _ABC_data is a C-style struct and your call ptr->print(); will be transformed to: _ABC_print(nullptr) which is alright while execution since you do not use this arg. UPDATE: (Thanks to Windows programmer for right comment) Such code is alright only for CPU which executes it. There is absolutely positively no sane reason to exploit this implementation feature. Because: Standard states it yields undefined behavior If you actually need ability to call member function without instance, using static keyword gives you that with all the portability and compile-time checks
2,505,365
2,505,376
Compiler error: memset was not declared in this scope
I am trying to compile my C program in Ubuntu 9.10 (gcc 4.4.1). I am getting this error: Rect.cpp:344: error: ‘memset’ was not declared in this scope But the problem is I have already included in my cpp file: #include <stdio.h> #include <stdlib.h> And the same program compiles fine under Ubuntu 8.04 (gcc 4.2.4). Please tell me what am I missing.
You should include <string.h> (or its C++ equivalent, <cstring>).
2,505,582
2,506,013
GCC exports decorated function name only from dll
I have a dll, it exports a function... extern "C" int __stdcall MP_GetFactory( gmpi::IMpUnknown** returnInterface ) { } I compile this with Code::Blocks GCC compiler (V3.4.5). Problem: resulting dll exports decorated function name... MP_GetFactory@4 This fails to load, should be plain old... MP_GetFactory I've researched this for about 4 hours. I think --add-stdcall-alias is the option to fix this. My Code::Blocks log shows... mingw32-g++.exe -shared -Wl,--out-implib=bin\Debug\libGainGCC.a -Wl,--dll obj\Debug\se_sdk3\mp_sdk_audio.o obj\Debug\se_sdk3\mp_sdk_common.o obj\Debug\Gain\Gain.o obj\Debug\Gain\gain.res -o bin\Debug\GainGCC.sem --add-stdcall-alias -luser32 ..so I think that's the correct option in there? But no luck. Dependancy Walker show only the decorated name being exported. I got It to kinda work by using __cdecl instead of __stdcall, the name is then exported ok, but the function corrupts the stack when called (because the caller expected the other calling convention).
Sorry to answer my own question, finally figured it out. Project/Build Options/Linker/Other Linker Options -Wl,--kill-at ...kills the decoration '@' symbol etc.
2,505,712
2,505,829
Trying to load a DLL with LoadLibrary and get R6034 "An application has made an attempt to load the C runtime library incorrectly"
I'm writing a wrapper program that loads Winamp input plugins. I've got it working well so far with quite a few plugins, but for some others, I get an error message at runtime when I attempt to call LoadLibrary on the plugin's DLL. (It seems to happen mostly with plugins that were included with Winamp.) A dialog appears and gives me the error code and message above. This happens, for example, with the in_flac.dll and in_mp3.dll plugins (which come with Winamp). Any ideas on how I can remedy this situation? EDIT: This basically iterates through the plugins in a directory and attempts to load and then free each one. Some plugins produce the error I mentioned above, while others do not. wstring path = GetSearchPath(); FileEnumerator e(path + L"in_*.dll"); while(e.MoveNext()) { wstring pluginPath = path + e.GetCurrent().cFileName; MessageBoxW(NULL, pluginPath.c_str(), L"Message", MB_OK); HINSTANCE dll = LoadLibraryW(pluginPath.c_str()); if(!dll) { pluginPath = wstring(L"There was an error loading \"") + wstring(e.GetCurrent().cFileName) + L"\":\n" + LastErrorToString(); MessageBoxW(NULL, pluginPath.c_str(), L"Error", MB_OK); continue; } FreeLibrary(dll); }
Starting from Visual Studio 2005, the C/C++ runtime MUST be put in the Windows side-by-side cache (C:\windows\WinSxS), so putting the CRT DLL's next to your exe doesn't work anymore (with one exception, see later). You MUST also refer to the CRT DLL's via a manifest file. This manifest file is generated by the linker and will have a name like myexe.exe.manifest or mydll.dll.manifest. Distribiute this manifest with your application/DLL or link it in the exe/dll using the mt command. The side-by-side cache and the manifest file system were introduced in Windows XP and are mainly intended to solve the DLL hell and to increase security. Not referring to the CRT using a manifest or not putting the CRT in the side-by-side cache will generate error 6034. If you still want to put the CRT DLL's next to your application, you could also use private assemblies, which means creating a kind of mini-side-by-side cache in the folder of your application. You can find additional information on MSDN.
2,506,085
2,506,095
Overload dereference operator
I'm trying to overload the dereference operator, but compiling the following code results in the error 'initializing' : cannot convert from 'X' to 'int': struct X { void f() {} int operator*() const { return 5; } }; int main() { X* x = new X; int t = *x; delete x; return -898; } What am I doing wrong?
You should apply dereference operator to a class type. In your code x has a pointer type. Write the following: int t = **x; or int t = x->operator*();
2,506,167
2,506,415
c++ macros with memory?
Is it possible to define macros write_foo(A); and read_foo(); so that: WRITE_FOO(hello); code_block_1; READ_FOO(); code_block_2; READ_FOO(); WRITE_FOO(world); code_block_3; READ_FOO(); code_block_4; READ_FOO(); expands into: code_block_1; hello; code_block_2; hello; code_boock_3; world; code_block_4; world; ? Thanks!
Macros cannot redefine other macros, but you can do it manually. #define FOO hello FOO // expands to hello #undef FOO #define FOO world FOO // expands to world #undef FOO #define FOO blah FOO // expands to blah Unfortunately, the #define + #undef combination cannot be encapsulated in any other structure that I am aware of.
2,506,632
2,506,644
C++ conditional compilation
I have the following code snippet: #ifdef DO_LOG #define log(p) record(p) #else #define log(p) #endif void record(char *data){ ..... ..... } Now if I call log("hello world") in my code and DO_LOG isn't defined, will the line be compiled, in other words will it eat up the memory for the string "hello world"? P.S. There are a lot of record calls in the program and it is memory sensitive, so is there any other way to conditionally compile so that it only depends on the #define DO_LOG?
This should be trivial to verify for yourself by inspecting the resulting binary. I would say "no", since the expression totally goes away, the compiler will never see the string (it's removed by the preprocessor's macro expansion).
2,506,793
2,506,800
C++: Life span of temporary arguments?
When creating a new instance of a MyClass as an argument to a function like so: class MyClass { MyClass(int a); }; myFunction(MyClass(42)); Does the standard make any guarantees on the timing of the destructor? Specifically, can I assume that it is going to be called before the next statement after the call to myFunction() ?
Temporary objects are destroyed at the end of the full expression they're part of. A full expression is an expression that isn't a sub-expression of some other expression. Usually this means it ends at the ; (or ) for if, while, switch etc.) denoting the end of the statement. In your example, it's the end of the function call. Note that you can extend the lifetime of temporaries by binding them to a const reference. Doing so extends their lifetime to the reference's lifetime: MyClass getMyClass(); { const MyClass& r = getMyClass(); // full expression ends here ... } // object returned by getMyClass() is destroyed here If you don't plan to change the returned object, then this is a nice trick to save a copy constructor call (compared to MyClass obj = getMyClass();), in case return value optimization was not being applied. Unfortunately it isn't very well known. (I suppose C++11's move semantics will render it less useful, though.)
2,506,909
2,506,923
C++ error: expected initializer before ‘&’ token
the following piece of C++ code compiled two years ago in a suse 10.1 Linux machine. #ifndef DATA_H #define DATA_H #include <iostream> #include <iomanip> inline double sqr(double x) { return x*x; } enum Direction { X,Y,Z }; inline Direction next(const Direction d) { switch(d) { case X: return Y; case Y: return Z; case Z: return X; } } inline ostream& operator<<(ostream& os,const Direction d) { switch(d) { case X: return os << "X"; case Y: return os << "Y"; case Z: return os << "Z"; } } ... ... Now, I am trying to compile it on Ubuntu 9.10 and I get the error: data.h:20: error: expected initializer before ‘&’ token which is referred to the line of: inline ostream& operator<<(ostream& os,const Direction d) the g++ used on this machine is: Using built-in specs. Target: x86_64-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.1-4ubuntu9' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --disable-werror --with-arch-32=i486 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu Thread model: posix gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9) Could you give me some hint about this error? Thanks P.D. If i do std::ostream, I get the errors: data.h:20: error: declaration of ‘operator<<’ as non-function data.h:20: error: ‘ostream’ was not declared in this scope data.h:20: error: ‘os’ was not declared in this scope data.h:20: error: expected primary-expression before ‘const’
As everything in the C++ standard library, ostream lives in the std namespace, so it's std::ostream. I believe that, if this used to compile, this was in error.
2,507,364
2,507,380
return by reference - which of the two is the correct one
i have the function: const A& f(...) {...} a. const A a1 = f(..); b. const A &a2 = f(...); which of the is the better one to use? in both cases, if i understand correctly, i prevent the possibility of modifying the returned object. in the first option, the copy constructor of A will be called - am i correct?
It depends on what you want. In the first case you create a new const object that is constructed from the returned reference. It will be a snapshot of what was returned and will be valid for its entire lifetime. In the second you just initialize a reference. This means that any changes to the original object will be visible through the reference but there is a danger that the referred object will be destroyed while the reference is still alive.
2,507,522
2,507,537
Porting C++-code from Windows to Unix: systemcalls colliding with name of functions
I'm porting some crufty C++ Windows-code to Linux, which uses functions called "open" and "close" inside every class... Very bad style, or? Luckily that wasn't a problem in windows, since their systemcalls are named different. When I try to call the systemcalls open() or close() I'm getting some compiler error about "no matching function for call for class:open()". I can't rename all our functions named "class::open" and "class::close" in the whole code, and I have to use open() and close() since I'm working with serial ports. So my question is: How can I tell the compiler, which open I mean? How can I escape or hide the namespace of a class in C++?
You can use ::open to refer to the open in the global namespace.
2,507,697
2,508,003
Is it "legal" for C++ runtime to call terminate() when the C++ code is used inside some non-C++ program?
In certain cases - especially when an exception escapes a destructor during stack unwinding - C++ runtime calls terminate() which must do something reasonable post-mortem and then exit the program. When a question "why so harsh" arises the answer is usually "there's nothing more reasonable to do in such error situations". That sounds reasonable if the whole program is in C++. Now what if the C++ code is in a library and the program that uses the library is not in C++? This happens quite often - for example I might have a native C++ COM component consumed by a .NET program. Once terminate() is called inside the component code the .NET program suddenly ends abnormally. The program author will first of all think "I don't care of C++, why the hell is this library make my program exit?" How do I handle the latter scenario when developing libraries in C++? Is it reasonable that terminate() unexpectedly ends the program? Is there a better way to handle such situations?
Why is the C++ runtime calling terminate()? It doesn't do it at random, or due to circumstances which cannot be defined and/or avoided when the code is written. It does it because your code does something that is defined to result in a call to terminate(), such as throwing an exception from a destructor during stack unwinding. There is a list in the C++ standard of all the situations which are defined to result in call to terminate(). If you don't want terminate() to be called, don't do any of those things in your code. The same applies to unexpected(), abort(), and so on. I don't think this is any different really from the fact that you have to avoid undefined behavior, or in general avoid writing code which is wrong. You also have to avoid behavior which is defined but undesirable. Perhaps you have a particular example where it is difficult to avoid a call to terminate(), but throwing an exception from a destructor during stack unwinding isn't it. Just don't throw exceptions out of destructors, ever. This means designing your destructors such that if they do something which might fail, the destructor catches the exception and your code continues in a defined state. There are some situations where your system will impolitely hack your process away at the knees because of something that your C++ code does (although not by calling terminate()). For example, if the system is overcommitting memory and the VMM can't honour the promises malloc/new have made, then your process might be killed. But that's a system feature, and probably applies equally to the other language that's calling your C++. I don't think there's anything you can (or need to) do about it, as long as your caller is aware that your library might allocate memory. In that circumstance it's not your code's fault the process died, it's the defined response of the operating system to low-memory conditions.
2,507,757
2,507,858
Hiding an entry from a QMenuBar in Qt4?
I can find no non-deprecated way of hiding an item in a menu bar in Qt4. This post: http://qt.nokia.com/developer/faqs/585 gives a method that uses deprecated Qt3 compatibility functions. Is there a better way?
QAction::setVisible() is what you are looking for: QAction* act = new QAction(tr("&Moo"), this); someMenu->addAction(act); // ... act->setVisible(false); To apply that to menus use their QAction* which you get either via QMenu::menuAction() or from QMenu::addMenu() (depending on what overload you use).
2,507,948
2,507,971
I need to randomize a number between two hex numbers, represented as strings
...and return the number as string. How can I do that? Is there any library for that?
You can use std::istringstring from <sstream> to convert the strings to integers. Then you can use rand or random to get a random number, which you can constrain to the interval using modular arithmetic, and then you can convert the number to a hexadecimal string using std::ostringstream. #include <sstream> #include <string> #include <cstdlib> int hexstr2int(const std::string& str) { int result; std::istringstream iss(str); iss >> result; return result; } std::string int2hexstr(int number) { std::ostringstream oss; oss << std::hex << number; return number.str(); } int randint(int lower, int upper) { int range = upper - lower; return ((rand()%range)+lower); } std::string randhexstr(const std::string& a, const std::string& b) { int lower = hexstr2int(a); int upper = hexstr2int(b); return int2hexstr(randint(lower,upper)); }
2,508,082
2,508,310
Recovering graceflly from a failed vsnprintf on msvc2008
I'm looking for a way to use some variant of vsnprintf() with a buffer that can possibly be longer than the input buffer without triggering an error to the user. So far I've found that vsnprintf() and its variants silently truncate the string when the buffer is too small but they don't return the actual length of the string so I can't try it again with a longer buffer. They return -1. On the other hand, the vsnprintf_s() variants, when faced with this error, call _VALIDATE_RETURN(("Buffer too small", 0), ERANGE, -1); Which in turn eventually calls _CrtDbgReportW(), possibly only in debug. They do this even before calling the user supplied "invalid parameter handler" All I want is to be able to recover with no user interaction by getting the actual size I need to allocate and calling the function again. is that possible?
The function you're looking for is _vscprintf (or _vscwprintf). These return the number of characters required without actually formatting anything.
2,508,284
2,508,377
C++ copy constructor and shallow copy
suppose I have a class with many explicit (statically allocated) members and few pointers that are allocated dynamically. When I declare a copy constructor in witch I make a deep copy of manually allocated members, I wouldn't like to copy each statically allocated member explicite. How can I use implicit (default) copy constructor functionality in explicit copy constructor?
Use containment: class outer { public: outer( const outer& other ) : members_( other_.members_ ), pmember_( deep_copy( other.pmember_ )) {} // DON'T FORGET ABOUT THESE TOO outer& operator=( const outer& ); ~outer(); private: struct inner { inner( int i, float f ) : int_( i ), float_( f ) {} int int_; float float_; }; inner members_; //< direct members something* pmember_; //< indirect member };
2,508,436
2,508,526
Fast sign in C++ float...are there any platform dependencies in this code?
Searching online, I have found the following routine for calculating the sign of a float in IEEE format. This could easily be extended to a double, too. // returns 1.0f for positive floats, -1.0f for negative floats, 0.0f for zero inline float fast_sign(float f) { if (((int&)f & 0x7FFFFFFF)==0) return 0.f; // test exponent & mantissa bits: is input zero? else { float r = 1.0f; (int&)r |= ((int&)f & 0x80000000); // mask sign bit in f, set it in r if necessary return r; } } (Source: ``Fast sign for 32 bit floats'', Peter Schoffhauzer) I am weary to use this routine, though, because of the bit binary operations. I need my code to work on machines with different byte orders, but I am not sure how much of this the IEEE standard specifies, as I couldn't find the most recent version, published this year. Can someone tell me if this will work, regardless of the byte order of the machine? Thanks, Patrick
How do you think fabs() and fabsf() are implemented on your system, or for that matter comparisons with a constant 0? If it's not by bitwise ops, it's quite possibly because the compiler writers don't think that would be any faster. The portability problems with this code are: float and int might not have the same endianness or even the same size. Hence also, the masks could be wrong. float might not be IEEE representation You break strict aliasing rules. The compiler is allowed to assume that a pointer/reference to a float and a pointer/reference to an int cannot point to the same memory location. So for example, the standard does not guarantee that r is initialized with 1.0 before it is modified in the following line. It could re-order the operations. This isn't idle speculation, and unlike (1) and (2) it's undefined, not implementation-defined, so you can't necessarily just look it up for your compiler. With enough optimisation, I have seen GCC skip the initialization of float variables which are referenced only through a type-punned pointer. I would first do the obvious thing and examine the emitted code. Only if that appears dodgy is it worth thinking about doing anything else. I don't have any particular reason to think that I know more about the bitwise representation of floats than my compiler does ;-) inline float fast_sign(float f) { if (f > 0) return 1; return (f == 0) ? 0 : -1; // or some permutation of the order of the 3 cases } [Edit: actually, GCC does make something of a meal of that even with -O3. The emitted code isn't necessarily slow, but it does use floating point ops so it's not clear that it's fast. So the next step is to benchmark, test whether the alternative is faster on any compiler you can lay your hands on, and if so make it something that people porting your code can enable with a #define or whatever, according to the results of their own benchmark.]
2,508,529
2,508,568
C++ how to store integer into a binary file?
I've got a struct with 2 integers, and I want to store them in a binary file and read it again. Here is my code: static const char *ADMIN_FILE = "admin.bin"; struct pw { int a; int b; }; void main(){ pw* p = new pw(); pw* q = new pw(); std::ofstream fout(ADMIN_FILE, ios_base::out | ios_base::binary | ios_base::trunc); std::ifstream fin(ADMIN_FILE, ios_base::in | ios_base::binary); p->a=123; p->b=321; fout.write((const char*)p, sizeof(pw)); fin.read((char*)q, sizeof(pw)); fin.close(); cout << q->a << endl; } The output I get is 0. Can anyone tell me what is the problem?
You probably want to flush fout before you read from it. To flush the stream, do the following: fout.flush(); The reason for this is that fstreams generally want to buffer the output as long as possible to reduce cost. To force the buffer to be emptied, you call flush on the stream.
2,508,605
2,508,659
Modifying a const through a non-const pointer
I'm a bit confused what happened in the following code: const int e = 2; int* w = ( int* ) &e; // (1) cast to remove const-ness *w = 5; // (2) cout &lt&lt *w &lt&lt endl; // (3) outputs 5 cout &lt&lt e &lt&lt endl; // (4) outputs 2 cout &lt&lt "w = " &lt&lt w &lt&lt endl; // (5) w points to the address of e cout &lt&lt "&e = " &lt&lt &e &lt&lt endl; In (1), w points to the address of e. In (2), that value was changed to 5. However, when the values of *w and e were displayed, their values are different. But if you print value of w pointer and &e, they have the same value/address. How come e still contained 2, even if it was changed to 5? Were they stored in a separate location? Or a temporary? But how come the value pointed by w is still the address of e?
As I said in my comment, once you modified the const value you are in undefined behaviour land, so it doesn't make much sense to talk about what is happening. But what the hell.. cout << *w << endl; // (3) outputs 5 cout << e << endl; // (4) outputs 2 At a guess, *w is being evaluated at runtime, but e is being treated as a compile time constant
2,508,796
2,508,814
C++ printf: newline (\n) from commandline argument
How print format string passed as argument ? example.cpp: #include <iostream> int main(int ac, char* av[]) { printf(av[1],"anything"); return 0; } try: example.exe "print this\non newline" output is: print this\non newline instead I want: print this on newline
No, do not do that! That is a very severe vulnerability. You should never accept format strings as input. If you would like to print a newline whenever you see a "\n", a better approach would be: #include <iostream> #include <cstdlib> int main(int argc, char* argv[]) { if ( argc != 2 ){ std::cerr << "Exactly one parameter required!" << std::endl; return 1; } int idx = 0; const char* str = argv[1]; while ( str[idx] != '\0' ){ if ( (str[idx]=='\\') && (str[idx+1]=='n') ){ std::cout << std::endl; idx+=2; }else{ std::cout << str[idx]; idx++; } } return 0; } Or, if you are including the Boost C++ Libraries in your project, you can use the boost::replace_all function to replace instances of "\\n" with "\n", as suggested by Pukku.
2,509,164
2,509,185
"Unhandled exception" error when using a loop inside thread
I got this error Unhandled exception at 0x0049b946 in Program.exe: 0xC0000005: Access violation reading location 0x00000090. and the error points to this line: // thread.hpp ln 56 void run() { f(); // here << } When trying to run this code: void frameFunc() { for(;;) { //..........do something. it is too long to paste. (calculations) } } int main() { boost::thread framethread(frameFunc); framethread.join(); //........ } The error will simply gone when I remove the loop in frameFunc. Any kind of help would be appreciated :)
The code that you showed looks valid. I think the problem is inside the code that is not shown.
2,509,499
2,510,081
How to use std::allocator in my own container class
I am trying to write a container class which uses STL allocators. What I currently do is to have a private member std::allocator<T> alloc_; (this will later be templated so that the user can pick a different allocator) and then call T* ptr = alloc_.allocate(1,0); to get a pointer to a newly allocated 'T' object (and used alloc_.construct to call the constructor; see the answer below). This works with the GNU C++ library. However, with STLPort on Solaris, this fails to do the right thing and leads to all sorts of bizarre memory corruption errors. If I instead do std::allocator_interface<std::allocator<T> > alloc_; then it is all working as it should. What is the correct way to use the stl::allocator? The STLPort/Solaris version fails to compile with g++, but is g++ right?
Something you might want to do is have your own custom allocator that you can use to see how the standard containers interact wit allocators. Stephan T. Lavavej posted a nice, simple one called the mallocator. Drop it into a test program that uses various STL containers and you can easily see how the allocator is used by the standard containers: http://blogs.msdn.com/vcblog/archive/2008/08/28/the-mallocator.aspx Not all of the interface functions in the mallocator (such as construct() and destroy()) are instrumented with trace output, so you might want to drop trace statements in there to more easily see how the standard containers might use those functions without resorting to a debugger. That should give you a good idea of how your containers might be expected to use a custom allocator.
2,509,668
2,509,680
Why using namespace std is necessary here?
#include <iostream> using namespace std; int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! return 0; } If I remove the 2nd statement,the build will fail. Why is it necessary?
Because cout and endl are contained inside the std namespace. You could remove the using namespace std line and put instead std::cout and std::endl. Here is an example that should make namespaces clear: Stuff.h: namespace Peanuts { struct Nut { }; } namespace Hardware { struct Nut { }; } When you do something like using namespace Hardware you can use Nut without specifying the namespace explicitly. For any source that uses either of these classes, they need to 1) Include the header and 2) specify the namespace of the class or put a using directive. The point of namespaces are for grouping and also to avoid namespace collisions. Edit for your question about why you need #include : #include <iostream> includes the source for cout and endl. That source is inside the namespace called std which is inside iostream.
2,509,734
2,510,872
Break down C++ code size
I'm looking for a nice Stack Overflow-style answer to the first question in the old blog post C++ Code Size, which I'll repeat below: I’d really like some tool (ideally, g++ based) that shows me what parts of compiled/linked code are generated from what parts of C++ source code. For instance, to see whether a particular template is being instantiated for hundreds of different types (fixable via a template specialization) or whether code is being inlined excessively, or whether particular functions are larger than expected.
It does seem like something like this should exist, but I haven't used anything like it. I can tell you how I'd go about scripting this together, though. There are probably swifter and/or sexier ways to do it. First some stuff that you may already know: The addr2line command takes in an address and can tell you where the source code that the machine code there implements. The executable needs to be built with debugging symbols, and you'll probably not want to optimize it much (-O0, -O1, or -Os is probably as high as you'd want to go at first anyway). addr2line has several flags, and you'll want to read its manual page, but you will definitely need to use -C or --demangle if you want to see C++ function names that make sense in the output. The objdump command can print out all kinds of interesting things about the stuff in many types of object files. One of the things it can do is print out a table representing the symbols in or referred to by an object file (including executables). Now, what you want to do with that: What you'll want to is for objdump to tell you the address and size of the .text section. This is where actual executable machine code lives. There are several ways to do this, but the easiest (for this, anyway) is probably for you to do: objdump -h my_exe | grep text That should result in something like: 12 .text 0000049 000000f000 0000000f000 00000400 2**4 If you didn't grep it it would give you a heading like: Idx Name Size VMA LMA File off Algn I think for executables the VMA and LMA should be the same, so it won't matter which you use, but I think LMA is the best. You'll also want the size. With the LMA and size you can repeatedly call addr2line asking for the source code origin of the machine code. I'm not sure how this would work if you passed an address that was within one instruction, but I think it should work. addr2line -e my_exe <address> The output from this will be a path/filename, a colon, and a line number. If you were to count the occurrence of each unique path/file:num you should be able to look at the ones that have the highest counts. Perl hashes using the path/file:num as the key and a counter as the value would be an easy way to implement this, though there are faster ways if you find that runs too slow. You could also filter out things that you can determine don't need to be included early. For displaying your output you may want to filter out different lines from the same function, but you may notice that different lines within one function have different counts, which could be interesting. Anyway, that could be done either by making addr2line tell you the function name or using objdump -t in the first step and work one function at a time. If you see that some template code or other code lines are showing up in your executables more often than you think they should then you can easily locate them and have a closer look. Macros and inline functions may show end up manifesting themselves differently than you expect. If you didn't know, objdump and addr2line are from the GNU binutils package, which includes several other useful tools.
2,509,742
2,509,761
An array problem in C++
To access the array indice at the xth position we can use some sort of illustration as shown below #include<iostream> using namespace std; int main(){ float i[20]; for(int j=0;j<=20;j++) i[j]=0; } However the following piece of code does not work #include<iostream> using namespace std; float oldrand[55]; int jrand; void advance_random(){ int j1; float new_random; for(j1=0;j1<=23;j1++){ int temp = j1+30; new_random = (oldrand[j1]) - (oldrand[temp]); if(new_random <0.0) new_random = new_random+1; oldrand[j1] = new_random; } for(j1=24;j1<=54;j1++){ new_random[j1] = oldrand[j1] - oldrand[j1-23]; if(new_random[j1]<0.0) new_random[j1] = new_random + 1; oldrand[j1]=new_random; } } I recieve the following error ga.cpp:20: error: invalid types ‘float[int]’ for array subscript ga.cpp:21: error: invalid types ‘float[int]’ for array subscript ga.cpp:22: error: invalid types ‘float[int]’ for array subscript I am not able to find a mistake in my code please help me
new_random isn't declared as an array of floats, it's declared as a float. The compiler is trying to tell you you can't index into a float.
2,509,863
2,509,954
how to compile boost thread library
I want to compile only the thread and regular expresession library of boost and I want both static and dynamic libs. Could you please let us know how to do that?
You can use bjam to build libraries. Just invoke it in your boost folder. With parameters bjam toolset={your toolset} variant={release|debug} threading=multi link={static|shared} {library name} Just replace values from {} with values of your choice. For toolset name you can check {your boost dir}\tools\build\v2\user-config.jam (you can set your toolset there and you will don't have to write it in command line).
2,509,969
2,519,104
Connect to an elevated COM server from a non-elevated process
We have a program which launches a child process that hosts a local COM server, which for various reasons must be launched elevated. Everything works fine so long as both the parent and the child process are elevated. However, we also want to run when the parent process is non-elevated. Launching the child process results in a UAC dialog (which is acceptable), and the child appears to start correctly and successfully calls CoRegisterClassObject. However, the parent process gets REGDB_E_CLASSNOTREG when calling CoCreateInstance with the same CLSID. I assume this is some sort of permissions issue. How can I register my class in the elevated server to allow it to be called from a non-elevated process?
Read The COM Elevation Moniker for couple of ways to access elevated out-of-proc server.
2,509,970
2,509,990
Cannot find sleep function
i'm new at C Programming (i learned c++) i want to create a process with windows.h at first i just want to start my main programm that creates a process ( --> starts an other programm) that's my code, but it doesn't really work, i removed every unnessasery line of code but "void sleep(700)" (or "sleep (700)" for testing if the windows methods work, but i get an error, that "sleep" cant be found. #include <iostream> #include <windows.h> #include <string> using namespace std; void main() { //bool ret; //startupinfo stupinfo; //prozess_information pro2info; //Getstartupinfo (&stupinfo); //createprozess(null, "C:\\bsss10\\betriebssystemePRA1.exe", null, null, false, create_new_console, null, // null, &stupinfo, &pro2info); sleep (700); cout<< "hello"; } thanks in advance
C (and C++) is case sensitive - sleep should be Sleep. Similar issues (and spelling) with your commented-out code.
2,510,089
2,521,772
How to monitor a directory for files in C++?
I need to monitor a directory which contains many files and a process reads and deletes the .txt files from the directory; once all the .txt files are consumed, the consuming process needs to be killed. How do I check if all the .txt files are consumed using C++? I am developing my application on Visual Studio on windows platform.
Since it was not required to perform action on each txt file deletion. I came up with following code: { intptr_t hFile; struct _finddata_t c_file; string searchSpec; for (size_t i = 0; i < dataPathVec.size(); ++i) { searchSpec = dataPathVec.at(i) + DIRECTORY_SEPERATOR + "*" + TXT_FILE_EXT; hFile = 0; while((hFile != -1L) || (ret != 0)) { hFile = _findfirst(searchSpec.c_str(), &c_file); Sleep(500); if (hFile != -1L) { ret = _findclose(hFile); } } } } It can monitor many folders and wait till all the txt files are deleted from all the monitored folders.
2,510,496
2,510,573
Exactly How Does My C++ Program Terminate When it Runs Out of Memory?
The following C++ program crashes on my Windows XP machine with a message "Abnormal program termination" class Thing {}; int main() { for (;;) new Thing(); } I would say it's an out of memory problem, except I'm not sure Windows gets near the limit. Is it Windows killing it on purpose? If so, how does it decide?
You're right it's an out-of-memory problem that causes your program to end. But it's not Windows that decides to end it with "Abnormal program termination". It's the C++ runtime ("msvcrt*.dll" on Windows) that raises the std::bad_alloc exception when new Thing fails to allocate memory. You can verify that with a simple change: #include <exception> #include <iostream> class Thing {}; int main() { try { for (;;) new Thing(); } catch(std::bad_alloc e) { std::cout << "ending with bad_alloc" << std::endl; } } This will end the program normally when the program is out of memory. If you don't catch that exception, the unhandled exception will be handled by the C++ runtime, thus creating that famous "Abnormal program termination" message (or something similar).
2,510,521
2,510,568
How to handle 'this' pointer in constructor?
I have objects which create other child objects within their constructors, passing 'this' so the child can save a pointer back to its parent. I use boost::shared_ptr extensively in my programming as a safer alternative to std::auto_ptr or raw pointers. So the child would have code such as shared_ptr<Parent>, and boost provides the shared_from_this() method which the parent can give to the child. My problem is that shared_from_this() cannot be used in a constructor, which isn't really a crime because 'this' should not be used in a constructor anyways unless you know what you're doing and don't mind the limitations. Google's C++ Style Guide states that constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. This solves the 'this-in-constructor' problem as well as a few others as well. What bothers me is that people using your code now must remember to call Init() every time they construct one of your objects. The only way I can think of to enforce this is by having an assertion that Init() has already been called at the top of every member function, but this is tedious to write and cumbersome to execute. Are there any idioms out there that solve this problem at any step along the way?
Use a factory method to 2-phase construct & initialize your class, and then make the ctor & Init() function private. Then there's no way to create your object incorrectly. Just remember to keep the destructor public and to use a smart pointer: #include <memory> class BigObject { public: static std::tr1::shared_ptr<BigObject> Create(int someParam) { std::tr1::shared_ptr<BigObject> ret(new BigObject(someParam)); ret->Init(); return ret; } private: bool Init() { // do something to init return true; } BigObject(int para) { } BigObject() {} }; int main() { std::tr1::shared_ptr<BigObject> obj = BigObject::Create(42); return 0; } EDIT: If you want to object to live on the stack, you can use a variant of the above pattern. As written this will create a temporary and use the copy ctor: #include <memory> class StackObject { public: StackObject(const StackObject& rhs) : n_(rhs.n_) { } static StackObject Create(int val) { StackObject ret(val); ret.Init(); return ret; } private: int n_; StackObject(int n = 0) : n_(n) {}; bool Init() { return true; } }; int main() { StackObject sObj = StackObject::Create(42); return 0; }
2,510,888
2,510,909
binary_search not working for a vector<string>
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(void) { string temp; vector<string> encrypt, decrypt; int i,n, co=0; cin >> n; for(i=0;i<n;i++) { cin >> temp; encrypt.push_back(temp); } for(i=0;i<n;i++) { cin >> temp; decrypt.push_back(temp); } for(i=0;i<n;i++) { temp = encrypt[i]; if((binary_search(decrypt.begin(), decrypt.end(), temp)) == true) ++co; } cout << co << endl; return 0; } It reads two equal lists of strings and should print out how many of the words in the first list are also found in the second list, simple. Not giving me the expexted results and i think the problem is in binary_search. Can you tell me why ?
Because the strings are not sorted in your vectors. Sort them first using std::sort.
2,511,312
2,511,380
Error handling and polymorphism
I have an application with some bunch of code like this: errCode = callMainSystem(); switch (errCode){ case FailErr: error("Err corresponding to val1\n"); case IgnoreErr: error("Err corresponding to val2\n"); ... ... default: error("Unknown error\n"); } The values are enum constants. Will it make some sense to have something like: // Error* callMainSystem() ... Some code return FaileErr(); // or some other error // handling code Error* err = callMainSystem(); err->toString(); The Error class may be made singleton as it only has to print error messages. What are the pros and cons of above methods,size is an important criteria as the application needs to be supported on embedded devices as well. P.S: I don't want to use exception handling because of portability issues and associated overheads.
IMHO polymorphism would be overkill here, as you don't actually need different behaviour, only use different data per error code. I would use a simple map<ErrorCode, string> instead to store the mappings from error codes to messages. The polymorphic solution would require the extra overhead of creation and destruction of Error instances. I can't see how to make Error a singleton; however, you could implement it as a sort of typesafe enum like in Java (i.e. a fixed number of constant instances). However, hardwiring their behaviour (e.g. printing error messages to stderr) can make it awkward to unit test your code.
2,511,379
2,516,600
Vacancy Tracking Algorithm implementation in C++
I'm trying to use the vacancy tracking algorithm to perform transposition of multidimensional arrays in C++. The arrays come as void pointers so I'm using address manipulation to perform the copies. Basically, there is an algorithm that starts with an offset and works its way through the whole 1-d representation of the array like swiss cheese, knocking out other offsets until it gets back to the original one. Then, you have to start at the next, untouched offset and do it again. You repeat until all offsets have been touched. Right now, I'm using a std::set to just fill up all possible offsets (0 up to the multiplicative fold of the dimensions of the array). Then, as I go through the algorithm, I erase from the set. I figure this would be fastest because I need to randomly access offsets in the tree/set and delete them. Then I need to quickly find the next untouched/undeleted offset. First of all, filling up the set is very slow and it seems like there must be a better way. It's individually calling new[] for every insert. So if I have 5 million offsets, there's 5 million news, plus re-balancing the tree constantly which as you know is not fast for a pre-sorted list. Second, deleting is slow as well. Third, assuming 4-byte data types like int and float, I'm using up actually the same amount of memory as the array itself to store this list of untouched offsets. Fourth, determining if there are any untouched offsets and getting one of them is fast -- a good thing. Does anyone have suggestions for any of these issues?
I found the best way which is about 12x faster than the set. I use a boost dynamic_bitset which lets me use the bitset and decide on the number of bits at runtime. Edit: In case anyone reads this in the future... this algorithm is not faster than a standard copy and write-back method of transposition with data elements that are normal sized (4-8 bytes). It is fast with larger data sizes (like if you are copy large structures e.g. 128 bytes).
2,511,724
2,511,878
Error with swig: undefined symbol: _ZN7hosters11hostersLink7getLinkEi
I'm trying to make a python binding for the this library: http://code.google.com/p/hosterslib/. I'm using swig, heres is the code: %module pyhosters %{ #include "hosters/hosters.hpp" %} %include "hosters/hosters.hpp" I run swig -c++ -python -o swig_wrap.cxx swig.i and I compile with g++ -O2 -fPIC -shared -o _pyhosters.so swig_wrap.cxx python-config --libs --cflags -lhosters -lcln -lhtmlcxx pkg-config libglog --libs --cflags -I/usr/include/python2.6 -Wall -Wextra But when I run python and I import it, I get: >>> import pyhosters Traceback (most recent call last): File "<input>", line 1, in <module> File "./pyhosters.py", line 7, in <module> import _pyhosters ImportError: ./_pyhosters.so: undefined symbol: _ZN7hosters11hostersLink7getLinkEi How can I solve that? Thanks.
That is the mangled name of: hosters::hostersLink::getLink(int) Make sure you have defined that function. Okay, I took a closer look at hosters 0.6. The header files declares two getLink methods: std::string getLink(void); std::string getLink(int n); But the source file only declares the first one: std::string hostersLink::getLink(void) {return Link;} But SWIG is creating wrappers for both of those functions which screws things up. I recommend doing one of two things: Delete the std::string getLink(int n); method as it's undefined. Add a definition for std::string getLink(int n) { ... }
2,511,921
2,511,939
Which of these will create a null pointer?
The standard says that dereferencing the null pointer leads to undefined behaviour. But what is "the null pointer"? In the following code, what we call "the null pointer": struct X { static X* get() { return reinterpret_cast<X*>(1); } void f() { } }; int main() { X* x = 0; (*x).f(); // the null pointer? (1) x = X::get(); (*x).f(); // the null pointer? (2) x = reinterpret_cast<X*>( X::get() - X::get() ); (*x).f(); // the null pointer? (3) (*(X*)0).f(); // I think that this the only null pointer here (4) } My thought is that dereferencing of the null pointer takes place only in the last case. Am I right? Is there difference between compile time null pointers and runtime according to C++ Standard?
Only the first and the last are null pointers. The others are results of reinterpret_cast and thus operate on implementation defined pointer values. Whether the behavior is undefined for them depends on whether there is an object at the address you casted to.
2,512,371
2,512,585
Extracting, then passing raw data into another class - How to avoid copying twice while maintaining encapsulation?
Consider a class Book with a stl container of class Page. each Page holds a screenshot, like page10.jpg in raw vector<char> form. A Book is opened with a path to a zip, rar, or directory containing these screenshots, and uses respective methods of extracting the raw data, like ifstream inFile.read(buffer, size);, or unzReadCurrentFile(zipFile, buffer, size). It then calls the Page(const char* stream, int filesize) constructor. Right now, it's clear that the raw data is being copied twice. Once to extract to Book's local buffer and a second time in the Page ctor to the Page::vector<char>. Is there a way to maintain encapsulation while getting rid of the middleman buffer?
In terms of code changes based on what you have already, the simplest is probably to give Page a setter taking a non-const vector reference or pointer, and swap it with the vector contained in the Page. The caller will be left holding an empty vector, but since the problem is excessive copying, presumably the caller doesn't want to keep the data: void Book::addPage(ifstream file, streampos size) { std::vector<char> vec(size); file.read(&vec[0], size); pages.push_back(Page()); // pages is a data member pages.back().setContent(vec); } class Page { std::vector<char> content; public: Page() : content(0) {} // create an empty page void setContent(std::vector<char> &newcontent) { content.swap(newcontent); } }; Some people (for example the Google C++ style guide) want reference parameters to be const, and would want you to pass the newcontent parameter as a pointer, to emphasise that it is non-const: void setContent(std::vector<char> *newcontent) { content.swap(*newcontent); } swap is fast - you'd expect it just to exchange the buffer pointers and sizes of the two vector objects. Alternatively, give Page two different constructors: one for the zip file and one for the regular file, and have it be responsible for reading its own data. This is probably the cleanest, and it allows Page to be immutable, rather than being modified after construction. But actually you might not want that, since as you've noticed in a comment, adding the Page to a container copies the Page. So there's some benefit to being able to modify the Page to add the data after it has been cheaply constructed in the container: it avoids that extra copy without you needing to mess with containers of pointers. Still, the setContent function could just as easily take the file stream / zip file info as take a vector. You could find or write a stream class which reads from a zipfile, so that Page can be responsible for reading data with just one constructor taking a stream. Or perhaps not a whole stream class, perhaps just an interface you design which reads data from a stream/zip/rar into a specified buffer, and Page can specify its internal vector as the buffer. Finally, you could "mess with containers of pointers". Make pages a std::vector<boost::shared_ptr<Page> >, then do: void Book::addPage(ifstream file, streampos size) { boost::shared_ptr<Page> page(new Page(file, size)); pages.push_back(page); // pages is a data member } A shared_ptr has a modest overhead relative to just a Page (it makes an extra memory allocation for a small node containing a pointer and a refcount), but is much cheaper to copy. It's in TR1 too, if you have some implementation of that other than Boost.
2,512,478
2,512,615
Will the following program cause any problem during compiling and execution process?
Will the following program cause any problem during compiling and execution process? class A{ public: virtual void foo(){} }; class B:public A{}; int main(){ B b; b.foo(); }
There will be no problems compiling or running this program. virtual functions can be overridden, but they don't have to be. If an object's class does not implement the virtual function, then the superclass will be checked for an implementation.
2,512,492
2,512,540
Why am I getting a segmentation fault?
If I pass a value greater than 100 as the second argument to BinaryInsertionSort, I get a segmentation fault. int BinarySearch (int a[], int low, int high, int key) { int mid; if (low == high) return low; mid = low + ((high - low) / 2); if (key > a[mid]) return BinarySearch (a, mid + 1, high, key); else if (key < a[mid]) return BinarySearch (a, low, mid, key); return mid; } void BinaryInsertionSort (int a[], int n) { int ins, i, j; int tmp; for (i = 1; i < n; i++) { ins = BinarySearch (a, 0, i, a[i]); if (ins < i) { tmp = a[i]; memmove (a + ins + 1, a + ins, sizeof (int) * (i - ins)); a[ins] = tmp; } } }
You are passing an array a[] in. it must be large enough that the values hi and low are in range. For example, if you pass an array of size 1 in, and low = 0. hi = 2, then mid = 1 which will be out of range (an array of size 1 can only have a[0] dereferenced, a[1] will be out of range).
2,512,512
2,512,527
Ambiguous call to Overloaded Function (const variety)
How do I fix this error? error C2668: 'std::_Tree<_Traits>::end' : ambiguous call to overloaded function My code looks like this: typedef map<int const *, float> my_map_t; my_map_t _test; my_map_t::const_iterator not_found = my_map_t::end(); if (_test.find(&iKeyValue) == not_found) { _test[iKeyValue] = 4 + 5; // not the actual code, but here for simplicity } The compiler complains that there's an ambiguous call to my_map_t::end(). This makes sense, because the only difference is the return type. Normally you can disambiguate the call by casting the parameters, but end() has no parameters. Any ideas?
From your code, it appears that my_map_t::end() is static (otherwise you'd have to call it on an instance, e.g. _test.end()). Edit: Jesse Beder is right in his comment to the question; the code doesn't make much sense, since _test is a type, not an object. Static member functions cannot be const-qualified (the const-qualification of a member function applies to the this pointer; static member functions have no this pointer).
2,512,528
2,512,792
FORTRAN function returning an array causes a segfault (calling from C++)
Basically, here's my problem. I'm calling someone else's FORTRAN functions from my C++ code, and it's giving me headaches. Some code: function c_error_message() character(len = 255) :: c_error_message errmsg(1:9) = 'ERROR MSG' return end That's the FORTRAN function. My first question is: Is there anything in there that would cause a segfault? If not, then second: What does that return? A pointer? I'm trying to call it with the following C statement: char *e = c_error_message_(); That causes a segfault. c_error_message(); That too causes a segfault. I declared c_error_message_() earlier on with the following code: extern"C" { char* c_error_message_(); } Would declaring a function with a different return type than the actual return type cause a segfault? I'm at a loss. Thanks for any replies.
Here is a method that works. When I tried to use the ISO C Binding with a function returning a string, the compiler objected. So if instead you use a subroutine argument: subroutine fort_err_message (c_error_message) bind (C, name="fort_err_message") use iso_c_binding, only: C_CHAR, C_NULL_CHAR character (len=1, kind=C_CHAR), dimension (255), intent (out) :: c_error_message character (len=255, kind=C_CHAR) :: string integer :: i string = 'ERROR MSG' // C_NULL_CHAR do i=1, 255 c_error_message (i) = string (i:i) end do return end subroutine fort_err_message The Fortran is a bit awkward because technically a C-string is an 1D array of characters. And example C code to demo that this works: #include <stdio.h> void fort_err_message ( char chars [255] ); int main ( void ) { char chars [255]; fort_err_message ( chars ); printf ( "%s\n", chars ); return 0; }
2,512,551
2,535,401
winHTTP GET request C++
I'll get right to the point. This is what a browser request looks like GET /index.html HTTP/1.1 This is what winHTTP does GET http://site.com/index.html HTTP/1.1 Is there any I can get the winHTTP request to be the same format as the regular one? I'm using VC++ 2008 if it makes any difference
Your code should look like this: // Specify an HTTP server. if (hSession) hConnect = WinHttpConnect( hSession, L"www.example.com", INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest( hConnect, L"GET", L"/path/resource.html", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); // Send a request. if (hRequest) bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); Can you post these three calls from your code? Note that the full URL is split in two - the host name is specified in the WinHttpConnect call, but the relative resource path is specified in the WinHttpOpenRequest call (as the pwszObjectName parameter). Based on your comment, it seems you are specifying the full URL in the WinHttpConnect call.
2,512,588
2,512,697
A method to change effective user id of a running program?
I'm writing a simple package manager and I'd like to automatically try sudo if the program isn't run as root. I found a function called seteuid, which looks likes it's exactly what I need, but I don't have the permissions to run it. So far all I can think of is a bash script to check before they get to the actual binary, but I'd like to do this all as C++ if possible. Is there any method of changing a processes's euid after it starts executing? Or a way to call sudo?
As bmargulies says in his answer, you can do this if you binary is owned by root and has the setuid bit set - but then you will need to implement the authentication part (checking that the user is actually allowed to become root) yourself too. You'd be essentially rewriting sudo within your application - the best way to handle this is to do what you suggested yourself, and install your application with a wrapper script that uses /usr/bin/id to check if it is root, and if not, call out to sudo (or su).
2,512,691
2,512,714
How to use references, avoid header bloat, and delay initialization?
I was browsing for an alternative to using so many shared_ptrs, and found an excellent reply in a comment section: Do you really need shared ownership? If you stop and think for a few minutes, I'm sure you can pinpoint one owner of the object, and a number of users of it, that will only ever use it during the owner's lifetime. So simply make it a local/member object of the owners, and pass references to those who need to use it. I would love to do this, but the problem becomes that the definition of the owning object now needs the owned object to be fully defined first. For example, say I have the following in FooManager.h: class Foo; class FooManager { shared_ptr<Foo> foo; shared_ptr<Foo> getFoo() { return foo; } }; Now, taking the advice above, FooManager.h becomes: #include "Foo.h" class FooManager { Foo foo; Foo& getFoo() { return foo; } }; I have two issues with this. First, FooManager.h is no longer lightweight. Every cpp file that includes it now needs to compile Foo.h as well. Second, I no longer get to choose when foo is initialized. It must be initialized simultaneously with FooManager. How do I get around these issues?
You can use a shared_ptr ( or any smart pointer, or even a dumb pointer) but not have shared ownership. E.g. class Foo; class FooManager { private: shared_ptr<Foo> foo; public: Foo& getFoo() { return *foo; } }; (This is just a sketch - you still need a setFoo(), and perhaps getFoo() should return a Foo *. But the point is that you're back to being lightweight, and you can control when foo is created.)
2,512,740
2,512,788
Hopping from a C++ to a Perl/Unix job
I have been a C++ / Linux Developer till now and I am adept in this stack. Of late I have been getting opportunities that require Perl, Unix (with knowledge of C++,shell scripting) expertise. Organizations are showing interest even though I don't have much scripting experience to boast off. The role is more in a Support, maintenance project involving SQL as well. Off late I am in a fix whether to forgo these offers or not. I don't know the dynamics of an IT organization and thus on one hand I fear that my C++ experience will be nullified and on the positive side I am getting to work on a new technology stack which will only add to my skill set. I am sure, most of you at some point of time have encountered such dilemmas and would have taken some decision. I want you to share your perspectives on such a scenario where a person is required to change his/her technology stack when changing his/her job. What are the merits and demerits in going with either of the choices? Also I know that C++ isn't going anywhere in the near future. What about perl? I have no clue as to what the future holds for perl developer? Whether there are enough opportunities for a perl developer? I am asking this question here because most of my fellow programmers face this career choice dilemma. EDIT: Since the last time I asked this question, I made up my mind to switch. I was just about to sign on the dotted line but some divine intervention made me seek some clarification about the working hours, and to my horror, the profile required me to work in shifts which I am never comfortable with. I was all the more livid because they didn't clarify this point earlier. It was a reputed organisation but still I gave them my piece of mind and said thank you very much. Thanks.
Regarding changing of stack, it definitely helps you long term in your career, both from extra experience available to offer to next employer to expanded job set you can qualify for to increased programming IQ due to knowing different points of view (e.g. Perl, for all its scripting origins, when used properly, has both OO and very nice functional paradigms available, but this point applies to any new technology). However, you must be willing to put extra effort in to actually learn new stack/environment/language, and to learn to do things new way (e.g. don't write C++ code in Perl :) - especially for that last benefit to kick in. Please note "environment" there - the jump involves for example learning new debuggers and debugging techniques (for me the hardest thing about C++ development after switching from Perl so far is probably doing effective gdb debugging after being used to flexibility/power of perl debugger). Personally I had to make this jump twice - from C developer to Perl and 10 years later Perl to C++. I learned a lot both times, and am not sorry I made the jump. The first jump was from IT role (Junior SA/Production with some C coding) to a full-on developer, the second was just a jump between different business teams. As for demerits, please be aware that you WILL lose your edge in whichever stack you're not currently using for a while. Not completely forget, but nowhere near where you left off - and that does not even count the fact that the stack may have naturally evolved in the time elapsed. Also, as I said, you MUST expect that to be effective, you have to put in a lot of effort to become fluent in idiomatics, philosophy and ecosystem of the new stack. E.g. simply learning Perl is a small piece of the puzzle - you need to become familiar with a large chunk of CPAN, just as you had to know STL etc... Not really a demerit as far as I'm concerned, but a point that needs to be kept in mind. As for opportunities for Perl developer, this was extensively covered on SO before. While the absolute # of jobs is likely less than that of Java or C++ ones, a high quality developer will always be in demand, and there's plenty of companies (including, or may be especially, in financial industry) heavily using serious Perl development (as opposed to simple administrative scripting). The language itself is developing and moving forward as well.
2,512,746
2,512,769
In C++, do variadic functions (those with ... at the end of the parameter list) necessarily follow the __cdecl calling convention?
I know that __stdcall functions can't have ellipses, but I want to be sure there are no platforms that support the stdarg.h functions for calling conventions other than __cdecl or __stdcall.
The calling convention has to be one where the caller clears the arguments from the stack (because the callee doesn't know what will be passed). That doesn't necessarily correspond to what Microsoft calls "__cdecl" though. Just for example, on a SPARC, it'll normally pass the arguments in registers, because that's how the SPARC is designed to work -- its registers basically act as a call stack that gets spilled to main memory if the calls get deep enough that they won't fit into register anymore. Though I'm less certain about it, I'd expect roughly the same on IA64 (Itanium) -- it also has a huge register set (a couple hundred if memory serves). If I'm not mistaken, it's a bit more permissive about how you use the registers, but I'd expect it to be used similarly at least a lot of the time. Why does this matter to you? The point of using stdarg.h and its macros is to hide differences in calling convention from your code, so it can work with variable arguments portably. Edit, based on comments: Okay, now I understand what you're doing (at least enough to improve the answer). Given that you already (apparently) have code to handle the variations in the default ABI, things are simpler. That only leaves the question of whether variadic functions always use the "default ABI", whatever that happens to be for the platform at hand. With "stdcall" and "default" as the only options, I think the answer to that is yes. Just for example, on Windows, wsprintf and wprintf break the rule of thumb, and uses cdecl calling convention instead of stdcall.
2,512,823
2,512,879
How to include only BOOST smart pointer codes into a project?
What are best practices to include boost smart pointer library only without adding all boost libraries into the project? I only want boost smart pointer library in my project and I don't want to check in/commit 200 MB source codes (boost 1.42.0) into my project repository just for that. What more, my windows mobile project itself doesn't even reach 10% of that size!
For just the smart pointer library, you have two options. Copy the headers you include in your source files (shared_ptr.hpp, etc.). Then copy over additional files until the project builds (make sure to maintain the directory structure). Use the boost bcp utility. For larger subsets, this tool saves a ton of time. The former will make sure the fewest number of files possible gets added your project. The latter is much faster for any substantial subset of boost, but it will likely include many files you don't need (compatibility headers for platforms your program doesn't support).
2,512,931
2,512,970
Catch Multiple Custom Exceptions? - C++
I'm a student in my first C++ programming class, and I'm working on a project where we have to create multiple custom exception classes, and then in one of our event handlers, use a try/catch block to handle them appropriately. My question is: How do I catch my multiple custom exceptions in my try/catch block? GetMessage() is a custom method in my exception classes that returns the exception explanation as a std::string. Below I've included all the relevant code from my project. Thanks for your help! try/catch block // This is in one of my event handlers, newEnd is a wxTextCtrl try { first.ValidateData(); newEndT = first.ComputeEndTime(); *newEnd << newEndT; } catch (// don't know what do to here) { wxMessageBox(_(e.GetMessage()), _("Something Went Wrong!"), wxOK | wxICON_INFORMATION, this);; } ValidateData() Method void Time::ValidateData() { int startHours, startMins, endHours, endMins; startHours = startTime / MINUTES_TO_HOURS; startMins = startTime % MINUTES_TO_HOURS; endHours = endTime / MINUTES_TO_HOURS; endMins = endTime % MINUTES_TO_HOURS; if (!(startHours <= HOURS_MAX && startHours >= HOURS_MIN)) throw new HourOutOfRangeException("Beginning Time Hour Out of Range!"); if (!(endHours <= HOURS_MAX && endHours >= HOURS_MIN)) throw new HourOutOfRangeException("Ending Time Hour Out of Range!"); if (!(startMins <= MINUTE_MAX && startMins >= MINUTE_MIN)) throw new MinuteOutOfRangeException("Starting Time Minute Out of Range!"); if (!(endMins <= MINUTE_MAX && endMins >= MINUTE_MIN)) throw new MinuteOutOfRangeException("Ending Time Minute Out of Range!"); if(!(timeDifference <= P_MAX && timeDifference >= P_MIN)) throw new PercentageOutOfRangeException("Percentage Change Out of Range!"); if (!(startTime < endTime)) throw new StartEndException("Start Time Cannot Be Less Than End Time!"); } Just one of my custom exception classes, the others have the same structure as this one class HourOutOfRangeException { public: // param constructor // initializes message to passed paramater // preconditions - param will be a string // postconditions - message will be initialized // params a string // no return type HourOutOfRangeException(string pMessage) : message(pMessage) {} // GetMessage is getter for var message // params none // preconditions - none // postconditions - none // returns string string GetMessage() { return message; } // destructor ~HourOutOfRangeException() {} private: string message; };
If you have multiple exception types, and assuming there's a hierarchy of exceptions (and all derived publicly from some subclass of std::exception,) start from the most specific and continue to more general: try { // throws something } catch ( const MostSpecificException& e ) { // handle custom exception } catch ( const LessSpecificException& e ) { // handle custom exception } catch ( const std::exception& e ) { // standard exceptions } catch ( ... ) { // everything else } On the other hand, if you are interested in just the error message - throw same exception, say std::runtime_error with different messages, and then catch that: try { // code throws some subclass of std::exception } catch ( const std::exception& e ) { std::cerr << "ERROR: " << e.what() << std::endl; } Also remember - throw by value, catch by [const] reference.
2,512,978
2,512,979
How to delete duplicate vectors within a multidimensional vector?
I have a vector of vectors: vector< vector<int> > BigVec; It contains an arbitrary number of vectors, each of an arbitrary size. I want to delete not duplicate elements of each vector, but any vectors that are the exact same as another. I don't need to preserve the order of the vectors so I can sort etc.. It should be a really simple problem to solve but I'm new to this, my (not-working) best effort: for (int i = 0; i < BigVec.size(); i++) { for (int j = 1; j < BigVec.size() ; j++ ) { if (BigVec[i][0] == BigVec [j][i]); { BigVec.erase(BigVec.begin() + j); i = 0; // because i get the impression deleting a j = 1; // vector messes up a simple iteration through } } } I think there might be a solution using Unique(), but I can't get that to work either.
Why not use unique? I think if you're having problems getting it to work it's because using std::unique requires that the range be sorted. So, something like std::vector<std::vector<int>> myVec; std::sort(myVec.begin(), myVec.end()); myVec.erase(std::unique(myVec.begin(), myVec.end()), myVec.end());
2,513,036
2,513,103
confusing fork system call
i was just checking the behaviour of fork system call and i found it very confusing. i saw in a website that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces #include <stdio.h> #include <sys/types.h> int main(void) { pid_t pid; char y='Y'; char *ptr; ptr=&y; pid = fork(); if (pid == 0) { y='Z'; printf(" *** Child process ***\n"); printf(" Address is %p\n",ptr); printf(" char value is %c\n",y); sleep(5); } else { sleep(5); printf("\n ***parent process ***\n",&y); printf(" Address is %p\n",ptr); printf(" char value is %c\n",y); } } the output of the above program is : *** Child process *** Address is 69002894 char value is Z ***parent process *** Address is 69002894 char value is Y so from the above mentioned statement it seems that child and parent have separet address spaces.this is the reason why char value is printed separately and why am i seeing the address of the variable as same in both child and parent processes.? Please help me understand this!
Basically the concept of virtual memory gives a view to the process as if it is the sole owner of the system. It feels it has access to the complete memory. But in reality, the OS gives it only a virtual memory which is mapped to the actual memory by the OS by using MMU. So, what happens in your case is, each process (parent and child) have their own address space. And this is separate for both. Now here, the address space refers to the virtual address space. So, though both in parent and child the same address is present, this is just the virtual address. and each maps to a different physical address. Hope it helps!!
2,513,108
2,513,117
How does extern work in c++?
This is from the <iostream>: namespace std { extern istream cin; ///< Linked to standard input extern ostream cout; ... It seems by using extern the data types defined in other namespaces will just be available?
extern is used to refer to a variable defined in a different compilation unit (for now, you can think of a compilation unit as a .cpp file). The statements in your example declare rather than define cin and cout. It is telling the compiler that the definition of these objects is found in another compilation unit (where they are not declared as extern).
2,513,138
2,520,958
ctrl+alt+del disable using c in window OS
How to disable ctrl+alt+del using C in Window OS? I tried SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, true, &bOldState, 0); but it doesn't working for me. Can you kindly guide me, so that I can make it possible.
The SPI_SETSCREENSAVERRUNNING parameter you are using is designed for screensavers on Windows 95. It works on Windows 95/98/ME and earlier. It does not work on Windows NT/2000/XP/Vista. The Ctrl-Alt-Del Hotkey combo can be disabled on Windows NT/2000/XP/Vista, but not usually from an application (user mode). Here are the mechanisms I'm familiar with. I haven't tried it on Windows 7, but I'm sure some or all of these techniques still work there. A GINA DLL can intercept the CAD sequence, but that may be overkill. It works because Windows registers the CAD Hotkey and sends a callback to GINA DLL to handle the action when you press it. A replacement GINA DLL can handle the callback differently (ignoring it), but it may be tricky to do this and remain compatible with other login mechanisms using other custom GINA DLLs. You can write a keyboard driver to intercept it. There is pretty good free source code on the net for it if you search for it. Look for the Ctrl2Cap driver and similar things. (This driver remaps the Caps Lock key and Ctrl keys to mimic old keyboard layouts.) You may also be able to "remap" keys in the registry to achieve your goal using the Scan Code Mapper. They added this in Windows 2000. It's limited, but workable in some situations. See this MSDN page for details. Pay attention to the limitations, though. For example, it requires a reboot for the change to take effect. Finally, you can disable the Task Manager and other features through an administrative setting using the Windows Admin Toolkit. It still interrupts everything to show you a "You can't do that" dialog. But at least it works to limit users' access to the machine. I wrote a device driver (option 2 on my list above) to block Ctrl-Alt-Del for Windows 95/98 (13 years ago), and later for Windows NT/2000/XP. I sold a lot of those. They're still around if you look.
2,513,151
2,513,168
Prossess state getting in c under window plateform
I am using CreateProcess function for creating the process, is there any option to get the current state of the process (running or not). Kindly guide me how can I make it possible.
Use OpenProcess function with that dwProcessId if it returns NULL Process is not running otherwise it will return handle to that process
2,513,228
2,513,302
Using glRotate and glTranslate with collision detection
Say I use glRotate to translate the current view based on some arbitrary user input (i.e, if key left is pressed then rtri+=2.5f) glRotatef(rtri,0.0f,1.0f,0.0f); Then I draw the triangle in the rotated position: glBegin(GL_TRIANGLES); // Drawing Using Triangles glVertex3f( 0.0f, 1.0f, 0.0f); // Top glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right glEnd(); // Finished Drawing The Triangle How do I get the resulting translated vertexes for use in collision detection? Or will I have to manually apply the transform myself and thus doubling up the work? The reason I ask is that I wouldn't mind implementing display lists.
The objects you use for collision detection are usually not the objects you use for display. They are usually simpler and faster. So yes, the way to do it is to maintain the transformation you're using manually but you wouldn't be doubling up the work because the objects are different.
2,513,239
2,513,360
does XMLDOMNodePtr::get_text() needs to be deallocated explicitly?
Greetings, Would like to know if we need to explicitly free the string allocated by a xmldomnodeptr using it's get_text() i.e. IXMLDOMNodePtr pNode; /*some code*/ BSTR sValue; pNode->get_text(&sValue); /*Should I do this?*/ SysFreeString(sValue); I cannot see any documentation stating the same, so I'm assuming we need to do explicit deallocation sysfreestring. But, Just need to be double sure :) Thanks in advance. Samrat Patil.
yes. You will have to free the string. BSTR bstrItemText = NULL; pIDOMNode->get_text(&bstrItemText); //Discl: return value is not checked here... if(bstrItemText) { ::SysFreeString(bstrItemText); bstrItemText = NULL; }
2,513,312
2,515,061
NUnit does not capture output of std::cerr
I have an nunit Test in C#, that calls a C# wrapper of a function in a C++ DLL. The C++ code uses std::cerr to output various messages. These messages cannot be redirected using nunit-console /out /err or /xml switch. In nunit (the GUI version) the output does not appear anywhere. I would like to be able to see this output in nunit (GUI version). Ideally I would like to be able to access this output in the Test. Thanks for any help.
Redirecting std::cerr is a matter of replacing the stream buffer with your own. It is important to restore in original buffer before we exit. I don't know what your wrapper looks like, but you can probably figure out how to make it read output.str(). #include <iostream> #include <sstream> #include <cassert> using namespace std; int main() { streambuf* buf(cerr.rdbuf()); stringstream output; cerr.rdbuf(output.rdbuf()); cerr << "Hello, world!" << endl; assert(output.str() == "Hello, world!\n"); cerr.rdbuf(buf); return 0; }
2,513,403
2,680,920
C++ Adobe Premiere video filter - print/draw/render text in output video frame
I want to write video filter for Adobe Premiere, and I need to print/draw/render some text into the output video frame. Looking into adobe premiere cs4 sdk I couldn't find a quick answer - is it possible? Please provide some samples! Thanks!
Some strategy I will try to implement: draw text with GDI into bitmap of frame size (VideoHandle->piSuites->ppixFuncs->ppixGetBounds) overlap frame pixels (VideoHandle->source) with bitmap pixels UPDATE alt text http://img413.imageshack.us/img413/6201/adobe.jpg Working sample, using Simple_Video_Filter sample from SDK... at the beginning of xFilter (short selector, VideoHandle theData) function create bitmap with text: TCHAR szBuffer[50] = {0}; RECT rect; HDC hdc = GetDC(NULL); int iLength = 0; iLength = wsprintf(szBuffer, "Hello World!"); BITMAPINFO bmInfo; memset(&bmInfo.bmiHeader,0,sizeof(BITMAPINFOHEADER)); bmInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); bmInfo.bmiHeader.biWidth=100; bmInfo.bmiHeader.biHeight=15; bmInfo.bmiHeader.biPlanes=1; bmInfo.bmiHeader.biBitCount = 32; bmInfo.bmiHeader.biCompression = BI_RGB; //create a temporary dc in memory. HDC pDC = GetDC(0); HDC TmpDC=CreateCompatibleDC(pDC); //create a new bitmap and select it in the memory dc BYTE *pbase; HBITMAP TmpBmp=CreateDIBSection(pDC, &bmInfo,DIB_RGB_COLORS,(void**)&pbase,0,0); HGDIOBJ TmpObj=SelectObject(TmpDC,TmpBmp); SetRect(&rect, 0, 0, 100, 15); DrawText(TmpDC, szBuffer, iLength, &rect, 32); in the middle where filter is set, instead of redSource = (redSource + redAdd) & 0x000000ff; greenSource = (greenSource + greenAdd) & 0x000000ff; blueSource = (blueSource + blueAdd) & 0x000000ff; use int x = vert; int y = horiz; if(x < 215 && y < 300) { COLORREF c = GetPixel(TmpDC,y-200, 215 - x); if(0 == ((int)GetRValue(c)+(int)GetGValue(c)+(int)GetBValue(c))) { redSource =255; greenSource =255; blueSource =255; } } and in the end of function clean memory SelectObject(TmpDC,TmpObj); DeleteDC(TmpDC); PS [some day :)] need to store bitmap in memory once instead of creating each time per frame...
2,513,502
2,513,568
Disable All I/O Ports on a Windows PC Using C?
Is it possible to disable all the I/O ports of the Windows PC my program is running on? If so, can that be done using C? The goal is that the user should not be able to interact with the PC through any path except for the network card while my program is running.
I doubt it's possible, and if it was you wouldn't want to do it anyway. First of, quite a few I/O ports are used for communication within the computer itself, so if you could disable them all, the computer would quickly quit working. The network adapter normally uses at least a couple, so if you did it, the network would quit working anyway. There are also (at least potentially) memory mapped peripherals anyway, so it wouldn't necessarily be effective -- other than the minor detail that the computer would almost certainly quit working until it was restarted, at which point the user would swear at you as he removed your software from his machine and vowed to never again use anything you developed. I don't see it now, but wasn't something about "blatantly offensive" once one of the reasons for voting to close a question? I'm not sure this qualifies, but it seems pretty close...
2,513,505
26,639,774
How to get available memory C++/g++?
I want to allocate my buffers according to memory available. Such that, when I do processing and memory usage goes up, but still remains in available memory limits. Is there a way to get available memory (I don't know will virtual or physical memory status will make any difference ?). Method has to be platform Independent as its going to be used on Windows, OS X, Linux and AIX. (And if possible then I would also like to allocate some of available memory for my application, someone it doesn't change during the execution). Edit: I did it with configurable memory allocation. I understand it is not good idea, as most OS manage memory for us, but my application was an ETL framework (intended to be used on server, but was also being used on desktop as a plugin for Adobe indesign). So, I was running in to issue of because instead of using swap, windows would return bad alloc and other applications start to fail. And as I was taught to avoid crashes and so, was just trying to degrade gracefully.
Having read through these answers I'm astonished that so many take the stance that OP's computer memory belongs to others. It's his computer and his memory to do with as he sees fit, even if it breaks other systems taking a claim it. It's an interesting question. On a more primitive system I had memavail() which would tell me this. Why shouldn't the OP take as much memory as he wants without upsetting other systems? Here's a solution that allocates less than half the memory available, just to be kind. Output was: Required FFFFFFFF Required 7FFFFFFF Required 3FFFFFFF Memory size allocated = 1FFFFFFF #include <stdio.h> #include <stdlib.h> #define MINREQ 0xFFF // arbitrary minimum int main(void) { unsigned int required = (unsigned int)-1; // adapt to native uint char *mem = NULL; while (mem == NULL) { printf ("Required %X\n", required); mem = malloc (required); if ((required >>= 1) < MINREQ) { if (mem) free (mem); printf ("Cannot allocate enough memory\n"); return (1); } } free (mem); mem = malloc (required); if (mem == NULL) { printf ("Cannot enough allocate memory\n"); return (1); } printf ("Memory size allocated = %X\n", required); free (mem); return 0; }
2,513,525
2,513,659
bitwise not operator
Why bitwise operation (~0); prints -1 ? In binary , not 0 should be 1 . why ?
You are actually quite close. In binary , not 0 should be 1 Yes, this is absolutely correct when we're talking about one bit. HOWEVER, an int whose value is 0 is actually 32 bits of all zeroes! ~ inverts all 32 zeroes to 32 ones. System.out.println(Integer.toBinaryString(~0)); // prints "11111111111111111111111111111111" This is the two's complement representation of -1. Similarly: System.out.println(Integer.toBinaryString(~1)); // prints "11111111111111111111111111111110" That is, for a 32-bit unsigned int in two's complement representation, ~1 == -2. Further reading: Two's complement This is the system used by Java (among others) to represent signed numerical value in bits JLS 15.15.5 Bitwise complement operator ~ "note that, in all cases, ~x equals (-x)-1"
2,513,741
2,513,767
C vs. C++ for performance in memory allocation
I am planning to participate in development of a code written in C language for Monte Carlo analysis of complex problems. This codes allocates huge data arrays in memory to speed up its performance, therefore the author of the code has chosen C instead of C++ claiming that one can make faster and more reliable (concerning memory leaks) code with C. Do you agree with that? What would be your choice, if you need to store 4-16 GB of data arrays in memory during calculation?
Definitely C++. By default, there's no significant difference between the two, but C++ provides a couple of things C doesn't: constructors/destructors. These let you automate most memory management, improving reliability. per-class allocators. These let you optimize allocation based on how particular objects are designed and/or used. This can be particularly useful if you need a large number of small objects (to give one obvious example). The bottom line is that in this respect, C provides absolutely no possibility of an advantage over C++. In the very worst case, you can do exactly the same things in the same ways.
2,513,897
2,513,937
How can I handle weird errors from calculating acos / sin / atan2?
Has anyone seen this weird value while handling sin / cos/ tan / acos.. math stuff? ===THE WEIRD VALUE=== -1.#IND00 ===================== void inverse_pos(double x, double y, double& theta_one, double& theta_two) { // Assume that L1 = 350 and L2 = 250 double B = sqrt(x*x + y*y); double angle_beta = atan2(y, x); double angle_alpha = acos((L2*L2 - B*B - L1*L1) / (-2*B*L1)); theta_one = angle_beta + angle_alpha; theta_two = atan2((y-L1*sin(theta_one)), (x-L1*cos(theta_one))); } This is the code I was working on. In a particular condition - like when x & y are 10 & 10, this code stores -1.#IND00 into theta_one & theta_two. It doesn't look like either characters or numbers :( Without a doubt, atan2 / acos / stuff are the problems. But the problem is, try and catch doesn't work either cuz those double variables have successfully stored some values in them. Moreover, the following calculations never complain about it and never break the program! I'm thinking of forcing to use this value somehow and make the entire program crash... So that I can catch this error.. Except for that idea, I have no idea how I should check whether these theta_one and theta_two variables have stored this crazy values. Any good ideas? Thank you in advance..
The "weird value" is NaN (not a number). The problem is because (L2*L2 - B*B - L1*L1) / (-2*B*L1) = 6.08112… is outside of the range [-1, 1] where acos is well-defined for real numbers. So NaN is returned. Are you sure the formula is correct? If you want to catch an NaN, the NaN needs to be a signaling NaN. For gcc, compile with the -fsignaling-nans option.
2,513,988
2,514,298
Iteration through std containers in openmp
I'm trying to use openmp to multithread a loop through std::set. When I write the following code - #pragma omp parallel for for (std::set<A>::const_iterator i = s.begin(); i != s.end(); ++i) { const A a = *i; operate(a); } I get this error: error: invalid type for iteration variable 'i' error: invalid controlling predicate error: invalid increment expression. Is there an another, correct way to iterate through std containers using openmp? I know I can use int i and iterate from 0 to s.size() and an iterator or operator[] in the loop body, but this looks much less clean.
Loop parallelization for stl iterators only works since OpenMP 3.0, and only for random access iterators (e.g. vector and deque). You should be able to do something like this: #pragma omp parallel { for (std::set<A>::const_iterator i = s.begin(); i != s.end(); ++i) { #pragma omp single nowait { operate(*i); } } } Overhead is quite big though because each thread iterates over the whole sequence (but only executes operate on some of it). Your method using an int i is more efficient. As an alternative take a look at GCC's parallel implementation of std::for_each. See my comment. EDIT: The STL Parallism TS, which will most likely be part of C++17, might be a good option in the future for iterating over standard containers.
2,514,050
2,514,358
How to update a uniform variable in GLSL
I am trying to get update the eye position in my shader from my appliaction but I keep getting error 1281 when I attempt this. I have no problems after the initialization just when i subsequently try to update the values. Here is my code: void GraphicsObject::SendShadersDDS(char vertFile [], char fragFile [], char filename []) { char *vs = NULL,*fs = NULL; vert = glCreateShader(GL_VERTEX_SHADER); frag = glCreateShader(GL_FRAGMENT_SHADER); vs = textFileRead(vertFile); fs = textFileRead(fragFile); const char * ff = fs; const char * vv = vs; glShaderSource(vert, 1, &vv, NULL); glShaderSource(frag, 1, &ff, NULL); free(vs); free(fs); glCompileShader(vert); glCompileShader(frag); program = glCreateProgram(); glAttachShader(program, frag); glAttachShader(program, vert); glLinkProgram(program); glUseProgram(program); LoadCubeTexture(filename, compressedTexture); GLint location = glGetUniformLocation(program, "tex"); glUniform1i(location, 0); glActiveTexture(GL_TEXTURE0); EyePos = glGetUniformLocation(program, "EyePosition"); glUniform4f(EyePos, EyePosition.X(),EyePosition.Y(), EyePosition.Z(), 1.0); DWORD bob = glGetError(); //All is fine here glEnable(GL_DEPTH_TEST); } And here's the function I call to update the eye position: void GraphicsObject::UpdateEyePosition(Vector3d& eyePosition){ glUniform4f(EyePos, eyePosition.X(),eyePosition.Y(), eyePosition.Z(), 1.0); DWORD bob = glGetError(); //bob equals 1281 after this call } I've tried a few ways now of updating the variable and this is the latest incarnation, thanks for viewing, all comments welcome. UPDATE: The error is not actually happening here at all, my fault for assuming it was, the error actually occurs when I draw a number of spring : for(int i = 0; i < 2; i++) { springs[i].Draw(); } When I draw the first one it's fine but I get an error when calling the second at the point where call glEnd() in response to glBegin(GL_LINE_STRIP). Sorry for the inconvenience as it wasn't the error I posted but atleast if anyone wants to know how to update uniform variables then it's here.
It is most likely this is caused by the fact that EyePos is invalid. What happens if you change the function to the following? void GraphicsObject::UpdateEyePosition(Vector3d& eyePosition) { EyePos = glGetUniformLocation(program, "EyePosition"); glUniform4f(EyePos, eyePosition.X(),eyePosition.Y(), eyePosition.Z(), 1.0); DWORD bob = glGetError(); } Edit: In response to your update the docs for glBegin/glEnd say that you'll get error 1280 (GL_INVALID_ENUM) if mode is set to an unacceptable value. Thus your problem is that GL_LINE_STRIP is not supported. GL_INVALID_OPERATION is generated if glBegin is executed between a glBegin and the corresponding execution of glEnd. GL_INVALID_OPERATION is generated if glEnd is executed without being preceded by a glBegin. GL_INVALID_OPERATION is generated if a command other than glVertex, glColor, glSecondaryColor, glIndex, glNormal, glFogCoord, glTexCoord, glMultiTexCoord, glVertexAttrib, glEvalCoord, glEvalPoint, glArrayElement, glMaterial, glEdgeFlag, glCallList, or glCallLists is executed between the execution of glBegin and the corresponding execution glEnd. GL_INVALID_OPERATION returns error 1282 and GL_INVALID_ENUM 1280 ... So a lot depends on what exact error you are getting ...
2,514,086
2,514,764
Run codes for only 60 times each second
I'm creating a directx application that relies on the system time (because it must be accurate), and I need to run lines of code for 60 times each second in the background (in a thread created by boost::thread). that's equal to 60 FPS (frame per second), but without depending on the main application frame rate. //................. void frameThread() { // I want to run codes inside this loop for *exactly* 60 times in a second. // In other words, every 16.67 (1000/60) milliseconds for(;;) { DoWork(); //......... } } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { initialize(); //.....stuffs boost::thread framethread(frameThread); //...... } Is there a way to do this? Any kind of help would be appreciated :)
Since 60 Hz is a common monitor refresh rate, it sounds like you want to enable V-Sync, instead of messing around with timers and sleeps. You mentioned you're using DirectX - If you're using DirectX 9, specify D3DPRESENT_INTERVAL_ONE when creating the device, and the application will synchronize to the monitor refresh rate. Usually this is 60 Hz - but it could also in theory be anything, such as 50Hz, 85Hz or 120Hz. You get a very nice tear-free display though - if you don't use V-sync, you'll likely get tearing artefacts when scrolling. This raises the problem: how do you make the game progress at the same speed if the framerate could vary so much? The answer is simple - use a high resolution timer (like QueryPerformanceCounter on Windows), and measure the time between each frame. Then you need to base any motion or movement off this 'delta time' value. This is a good thing to do anyway, even with a fixed framerate - it prevents your game suddenly running in slow motion if the computer is slow and the player only gets 20fps. Here's an example of moving an object horizontally at 100 pixels per second, regardless of the framerate: object.x += 100.0f * delta_time; // same speed no matter the framerate This IMO is a much better way of doing this, especially given it's tearing-free, framerate-independent, and synchronises with the user's monitor, not some arbitrary framerate you set yourself.
2,514,090
2,514,117
How to modify Registry of window OS from c or c++
I want to modify the registry of window OS using c. kindly guide me or give me some hints so that I can make it possible.
You need to use Win32 APIs such as RegOpenKeyEx for doing this.