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
1,390,073
1,390,115
Variable-length objects: Ever a good idea?
My application uses a large amount of Panda objects. Each Panda has a list of Bamboo objects. This list does not change once the Panda is initialized (no Bamboo objects are added or removed). Currently, my class is implemented as follows: class Panda { int a; int b; int _bambooCount; Bamboo* _bamboo; Panda (int count, Bamboo* bamboo) { _bambooCount = count; _bamboo = new Bamboo[count]; // ... copy bamboo into the array ... } } To alleviate the overhead of allocating an array of Bamboo objects, I could implement this class as follows -- basically, instead of creating objects via the regular constructor, a construction method allocates a single memory block to hold both the Panda object and its Bamboo array: class Panda { int a; int b; Panda () { // ... other initializations here ... } static Panda *createPanda (int count, Bamboo* bamboo) { byte* p = new byte[sizeof(Panda) + sizeof(Bamboo) * count]; new (p) Panda (); Bamboo* bamboo = (Bamboo*) p + sizeof(Panda); // ... copy bamboo objects into the memory // behind the object... return (Panda*)p; } } Can you foresee any problems with the second design, other than the increased maintenance effort? Is this an acceptable design pattern, or simply a premature optimization that could come back to bite me later?
C++ gives you another option. You should consider using std::vector. class Panda { int a; int b; std::vector<Bamboo> bamboo; // if you do not want to store by value: //std::vector< shared_ptr<Bamboo> > bamboo; Panda (int count, Bamboo* bamb) : bamboo( bamb, bamb+count ) {} } If you want to store Panda and Bamboos in continuous memory you could use solution from this article. The main idea is to overload operator new and operator delete.
1,390,340
1,390,660
How can I use std::remove on a container with std::tr1::weak_ptr?
If I had a STL container, say a list of pointers I could remove them like in the exmple below. With a container of weak_ptrs this does not work, because they cannot be compared, as they need to be locked first. What can I do? void MyClass::RemoveItem(std::tr1::weak_ptr<Item> const & pItem) { mylist.remove(pItem); }
For one thing, you could just define operator == for any weak_ptr. I'm sure there's a reason this is not implemented, it can probably bite you at a later point. template <typename T> bool operator == (const std::tr1::weak_ptr<T>& a, const std::tr1::weak_ptr<T>& b) { return a.lock() == b.lock(); } ... and you'll be able to just call remove() as usual. This is a little bit extreme I guess. If you stick to the remove_if() approach, you could get rid of the bind magic* by using function object: struct EqPredicate { const boost::weak_ptr<Item>& theItem; EqPredicate(const boost::weak_ptr<Item>& item) : theItem(item) { } bool operator () (const boost::weak_ptr<Item>& p) const { return p.lock() == theItem.lock(); } }; and then use it like this: mylist.remove_if(EqPredicate(pItem)); It looks like more code, but you can compress the EqPredicate class, it's mostly hollow. Also, it could be made template to use it with lists containing types other than Item. Oh, and do pass you weak_ptrs by reference everywhere including your comparison function. *bind is not free performance-wise. If you expect a lot of Remove() calls and care much about performance it might be good to avoid it.
1,390,401
1,390,438
Doing pointer math in a c++ class: Is it "legit"?
Ah-hoi, hoi, I'm wondering if it's ok to do something like the following: class SomeClass { int bar; }; SomeClass* foo = new SomeClass(); int offset = &(foo->bar) - foo; SomeClass* another = new SomeClass(); *(another+offset) = 3; // try to set bar to 3 Just Curious, Dan O
I suppose tecnically it might work out. However, there are several problems. bar is private. You are mixing pointers of different types (pointer arithmetic relies on the pointer type: int* + 1 and char* + 1 have different results because int and char have a different size). Have you also considered pointers to members: #include <cassert> struct SomeClass { int bar; }; int main() { int SomeClass::*mem_ptr = &SomeClass::bar; SomeClass foo; foo.*mem_ptr = 3; assert(foo.bar == 3); }
1,390,471
1,390,497
How to write a MultiPart download C++ program
I want to write a C++ program to download files with HTTP. For the sake of learning I would like to implement multipart downloading in my program the way DownThemAll! does. It is not possible to do lseek on a linux socket. I suppose it would be some HTTP option that we would need to specify, telling where to start downloading the file from. Thus we could have multiple connections open to the server. Is it right? What are the HTTP headers for doing so?
I suggest you take a look at section 14.35.1 Byte Ranges of the HTTP spec: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1,390,508
1,390,516
HTTP parsing library for linux C++
can anyone suggest a good HTTP parsing library for linux?
libcurl? It supports most web-based protocols, widely used, and stable. Available on most Linux distributions and should be around for Windows too. It supports both a simplified interface for quick-and-dirty implementations as well as an advanced interface for a robust implementation.
1,390,606
1,390,732
C++ static operator overloading
Is it possible to overload C++ class operators in the static context? e.g. class Class_1{ ... } int main() { Class_1[val]... }
If you are looking for metaprogramming using the built-in operator: Such a thing isn't possible - the built-in operators operate on runtime values, not on compile time values. You may use boost::mpl for that, and instead of using the built-in operators, use its templates, like at for op[], plus<a, b> for op+ etc. int main() { using boost::mpl::vector; using boost::mpl::at_c; using boost::mpl::plus; using boost::mpl::int_; typedef vector<int, bool, char, float> Class_1; typedef vector< int_<1>, int_<2> > Numeric_1; at_c<Class_1, 0>::type six = 6; typedef plus<at_c<Numeric_1, 0>::type ,at_c<Numeric_1, 1>::type>::type r; int i3[r::value] = { 4, 5, 6 }; return ((i3[0] + i3[1] + i3[2]) * six) == 90; }
1,390,703
1,391,479
Enumerate over an enum in C++
In C++, Is it possible to enumerate over an enum (either runtime or compile time (preferred)) and call functions/generate code for each iteration? Sample use case: enum abc { start a, b, c, end } for each (__enum__member__ in abc) { function_call(__enum__member__); } Plausible duplicates: C++: Iterate through an enum Enum in C++ like Enum in Ada?
To add to @StackedCrooked answer, you can overload operator++, operator-- and operator* and have iterator like functionality. enum Color { Color_Begin, Color_Red = Color_Begin, Color_Orange, Color_Yellow, Color_Green, Color_Blue, Color_Indigo, Color_Violet, Color_End }; namespace std { template<> struct iterator_traits<Color> { typedef Color value_type; typedef int difference_type; typedef Color *pointer; typedef Color &reference; typedef std::bidirectional_iterator_tag iterator_category; }; } Color &operator++(Color &c) { assert(c != Color_End); c = static_cast<Color>(c + 1); return c; } Color operator++(Color &c, int) { assert(c != Color_End); ++c; return static_cast<Color>(c - 1); } Color &operator--(Color &c) { assert(c != Color_Begin); return c = static_cast<Color>(c - 1); } Color operator--(Color &c, int) { assert(c != Color_Begin); --c; return static_cast<Color>(c + 1); } Color operator*(Color c) { assert(c != Color_End); return c; } Let's test with some <algorithm> template void print(Color c) { std::cout << c << std::endl; } int main() { std::for_each(Color_Begin, Color_End, &print); } Now, Color is a constant bidirectional iterator. Here is a reusable class i coded while doing it manually above. I noticed it could work for many more enums, so repeating the same code all over again is quite tedious // Code for testing enum_iterator // -------------------------------- namespace color_test { enum Color { Color_Begin, Color_Red = Color_Begin, Color_Orange, Color_Yellow, Color_Green, Color_Blue, Color_Indigo, Color_Violet, Color_End }; Color begin(enum_identity<Color>) { return Color_Begin; } Color end(enum_identity<Color>) { return Color_End; } } void print(color_test::Color c) { std::cout << c << std::endl; } int main() { enum_iterator<color_test::Color> b = color_test::Color_Begin, e; while(b != e) print(*b++); } Implementation follows. template<typename T> struct enum_identity { typedef T type; }; namespace details { void begin(); void end(); } template<typename Enum> struct enum_iterator : std::iterator<std::bidirectional_iterator_tag, Enum> { enum_iterator():c(end()) { } enum_iterator(Enum c):c(c) { assert(c >= begin() && c <= end()); } enum_iterator &operator=(Enum c) { assert(c >= begin() && c <= end()); this->c = c; return *this; } static Enum begin() { using details::begin; // re-enable ADL return begin(enum_identity<Enum>()); } static Enum end() { using details::end; // re-enable ADL return end(enum_identity<Enum>()); } enum_iterator &operator++() { assert(c != end() && "incrementing past end?"); c = static_cast<Enum>(c + 1); return *this; } enum_iterator operator++(int) { assert(c != end() && "incrementing past end?"); enum_iterator cpy(*this); ++*this; return cpy; } enum_iterator &operator--() { assert(c != begin() && "decrementing beyond begin?"); c = static_cast<Enum>(c - 1); return *this; } enum_iterator operator--(int) { assert(c != begin() && "decrementing beyond begin?"); enum_iterator cpy(*this); --*this; return cpy; } Enum operator*() { assert(c != end() && "cannot dereference end iterator"); return c; } Enum get_enum() const { return c; } private: Enum c; }; template<typename Enum> bool operator==(enum_iterator<Enum> e1, enum_iterator<Enum> e2) { return e1.get_enum() == e2.get_enum(); } template<typename Enum> bool operator!=(enum_iterator<Enum> e1, enum_iterator<Enum> e2) { return !(e1 == e2); }
1,390,913
1,390,922
Are static variables in a base class shared by all derived classes?
If I have something like class Base { static int staticVar; } class DerivedA : public Base {} class DerivedB : public Base {} Will both DerivedA and DerivedB share the same staticVar or will they each get their own? If I wanted them to each have their own, what would you recommend I do?
They will each share the same instance of staticVar. In order for each derived class to get their own static variable, you'll need to declare another static variable with a different name. You could then use a virtual pair of functions in your base class to get and set the value of the variable, and override that pair in each of your derived classes to get and set the "local" static variable for that class. Alternatively you could use a single function that returns a reference: class Base { static int staticVarInst; public: virtual int &staticVar() { return staticVarInst; } } class Derived: public Base { static int derivedStaticVarInst; public: virtual int &staticVar() { return derivedStaticVarInst; } } You would then use this as: staticVar() = 5; cout << staticVar();
1,390,991
1,391,277
Simulating static constructors in C++?
Is there anyway I can modify this code example #include <stdlib.h> #include <iostream> class Base { public: Base() { if(!m_initialized) { static_constructor(); m_initialized = true; } } protected: virtual void static_constructor() { std::cout << "Base::static_constructor()\n"; } private: static bool m_initialized; }; bool Base::m_initialized = false; class Derived : public Base { void static_constructor() { std::cout << "Derived::static_constructor()\n"; } }; int main(int argc, char** argv) { Derived d; return(EXIT_SUCCESS); } So that Derived::static_constructor() gets called instead of the Base's? I want to initialize a bunch of static variables, and the most logical place to do it is somewhere in the class.
I adopted this solution from the solution by Martin V Lowis. The main differences are that it uses multiple inheritance, and the CRTP: template<class T> class StaticInitializer : public T { static bool initialized; public: StaticInitializer(){ if(!initialized){ T::static_constructor(); initialized=true; } } }; template<class T> bool StaticInitializer<T>::initialized; class Base : public StaticInitializer<Base> { public: static void static_constructor() { std::cout << "Base::static_constructor()\n"; } }; static Base _base; class Derived : public Base, public StaticInitializer<Derived> { public: static void static_constructor() { std::cout << "Derived::static_constructor()\n"; } }; static Derived _derived; Each concrete subclass of StaticInitializer gets it's own static constructor initialisation method, but you keep the advantage of having true inheritance.
1,391,227
1,391,264
What is a "set" in C++? When are they useful?
I'm having a hard time conceptualizing c++ sets, actually sets in general. What are they? How are they useful?
Don't feel bad if you have trouble understanding sets in general. Most of a degree in mathematics is spent coming to terms with set theory: http://en.wikipedia.org/wiki/Set_theory Think of a set as a collection of unique, unordered objects. In many ways it looks like a list: { 1, 2, 3, 4 } but order is unimportant: { 4, 3, 2, 1} = { 1, 2, 3, 4} and repetitions are ignored: { 1, 1, 2, 3, 4 } = { 1, 2, 3, 4} A C++ set is an implementation of this mathematical object, with the odd feature that is is sorted internally. But this is just a detail of implementation, and is not relevant to understanding the data structure. The sorting is just for speed.
1,391,304
1,391,320
Can I cast an array like this?
Example code: #include <cstdlib> #include <iostream> using namespace std; class A { public: A(int x, int y) : x(x), y(y) {} int x, y; }; class B { public: operator A() { return A(x,y); } float x, y; }; void func1(A a) { cout << "(" << a.x << "," << a.y << ")" << endl; } void func2(A *a, int len) { for(int i=0; i<len; ++i) { cout << "(" << a->x << "," << a->y << ")"; } cout << endl; } int main(int argc, char** argv) { B b[10]; func1(b[0]); //func2(b, 10); return(EXIT_SUCCESS); } func1 works as expected, but func2 throws a compile-time error. Is there anything I can add to class B to make this work? I suspect not, but it doesn't hurt to ask, right? I assume it won't work because the size of A is different from the size of B?
When you pass array to a method you are only passing the address of the first element not the actual copy of the array nor the first element. In func1 you pass first element of array which is object of class B. Because B has operator A() it can convert B to A and new object of class A is passed to func1 In func2 you pass pointer to an array of B objects which is not the same as array of A objects so you get error. To solve it you could have a transformation method that takes pointer to array of B's and iterators over it and for each calls func1 or something like that.
1,391,426
1,391,430
Are member functions guaranteed to be ready before the creation of any object?
Consider this example: #include <iostream> class myclass { public: void print() { std::cout << "myclass"; } }; int main() { myclass* p = 0x0; // any address p->print(); // prints "myclass" } I didn't call the member function print through an object of type myclass. Instead I called it from a pointer to a random place in memory. Is this a defined behavior? That is, is the member function guaranteed to be executed before the creation of any object of type myclass?
Dereferencing a null (0) pointer is invoking undefined behaviour. The program can do anything it likes, including work as expected. In part, you get away with it here because the print() member function does not reference any member variables (there aren't any), but the compiler could still have generated code that would crash on you. And if the member function did reference any member variables, you would be severely into undefined behaviour. It probably isn't worth trying to work out the extent of the what you can do because you are invoking undefined behaviour, which can vary from compiler to compiler, version to version, platform to platform, run to run.
1,391,504
1,430,020
deflateEnd error 'no msg' kind: 'Z_DATA_ERROR': -3
I have a program that links in zlib v1.2.3 and it got the following error: deflateEnd error 'no msg' kind: 'Z_DATA_ERROR': -3 The program has work successfully with lots of different files to be compressed. Does anyone know what the 'no msg' of kind Z_DATA_ERROR means and how one would go about debugging it?
This means that deflateEnd() was incorrectly called before deflate() had been called enough times to consume all the input or produce all the output. Solution is to figure out why the program did not keep calling deflate() sufficient times. In my case, it was a fencepost error and the final calls to deflate() that specify to flush any remaining output and finish consuming all the input were dropped.
1,391,549
1,395,589
Good way to send result of 'uname -a' to a stream?
What is a good way to call 'uname -a' from a C++ program and send the results to a stream? I looked at system() and exec(), but they do not seem to give access to the stdout of the call. Thanks. -William
Why not just retrieve the strings directly from the struct utsname returned from the uname(2) system call found on most Unix/Unix-like platforms? No need to fork a "uname -a" process.
1,391,641
1,391,701
Why does read of /proc/cpuinfo seem to not advance file position?
I have the following code which ends up forever reading '/proc/cpuinfo' as it keeps getting the same result every read. Why doesn't the file pointer get advanced and reach eof ever? Seems this special file has different semantics. const int bufSize = 4096; char buf[bufSize + 1]; const string cpuInfo = "/proc/cpuinfo"; int cpuFD = ::open(cpuInfo.c_str(), O_RDONLY); if (cpuFD == -1) { logOutputStream << "Failed attempt to open '" << cpuInfo << "': " << strerror(errno) << endl; } else { assert(bufSize <= SSIZE_MAX); logOutputStream << "Contents of: '" << cpuInfo << "'.\n"; for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) { if (nRead == -1) { logOutputStream << "Failed attempt to read '" << cpuInfo << "': " << strerror(errno) << endl; break; } else { buf[nRead] = '\0'; logOutputStream << buf; } } if (::close(cpuFD) == -1) { logOutputStream << "Failed attempt to close '" << cpuInfo << "': " << strerror(errno) << endl; } }
for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) { is wrong. You're using read as an initializer, so read is only being called once, not once per loop. After that, you're just looping forever printing it out (because nothing is changing nRead).
1,391,670
1,391,713
Named Pipe strategies with dynamic memory?
Hokay so I have an application where I need some IPC... I'm thinking named pipes are the way to go because they are so easy to use. Anyways, I have a question about how to handle dynamic memory using named pipes. Say I have a class such as this: class MyTestClass { public: MyTestClass() { _data = new int(4); } int GetData() { return *_data; } int GetData2() { return _data2; } private: int* _data; int _data2; }; Now when I create a buffer full of MyTestClass objects then send them over the pipe, I'm obviously losing _data in the destination process and getting garbage. Is there some strategy to this that I should use? I can use value types for simple cases, but for many complex classes I need to use some sort of dynamic memory and I like pointers. Or, should I just look at using shared memory instead? Thanks
Both named pipes and shared memory have similar issues: You need to serialize the contents of the structure into the on the sending side and deserialize the structure from the on the receiving side. The serialization process is essentially identical whether you're using named pipes or shared memory. For embedded pointers (like _data and _data2) you need to serialize the contents of the pointer in a consistent fashion. There are lots of serialization strategies that you could use, depending on how your structures are laid out in memory and how efficient your IPC has to be. Or you could use DCE RPC and let the RPC marshaling code handle the complexities for you.
1,391,708
1,391,725
Is compile-time "strlen()" effective?
Sometimes it is necessary to compare a string's length with a constant. For example: if ( line.length() > 2 ) { // Do something... } But I am trying to avoid using "magic" constants in code. Usually I use such code: if ( line.length() > strlen("[]") ) { // Do something... } It is more readable, but not efficient because of the function call. I wrote template functions as follow: template<size_t N> size_t _lenof(const char (&)[N]) { return N - 1; } template<size_t N> size_t _lenof(const wchar_t (&)[N]) { return N - 1; } // Using: if ( line.length() > _lenof("[]") ) { // Do something... } In a release build (VisualStudio 2008) it produces pretty good code: cmp dword ptr [esp+27Ch],2 jbe 011D7FA5 And the good thing is that the compiler doesn't include the "[]" string in the binary output. Is it a compiler specific optimisation or is it a common behavior?
The capability to inline a function call is both a compiler-specific optimization and a common behavior. That is, many compilers can do it, but they aren't required to.
1,391,737
1,391,792
Using inline assembly from c++
Just to experiment assembly in C++, I tried the following, which is causing the application to crash: int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { __asm { push 5000 call Sleep } ... } the assembly part of code is supposed to act like the following line Sleep(5000); What am I doing wrong? edit: I am getting an Access Violation.
I just checked the assembly code in VC++ 6. You have to call the routine like this: call dword ptr [Sleep]
1,391,746
1,397,588
How to easily indent output to ofstream?
Is there an easy way to indent the output going to an ofstream object? I have a C++ character array that is null terminate and includes newlines. I'd like to output this to the stream but indent each line with two spaces. Is there an easy way to do this with the stream manipulators like you can change the base for integer output with special directives to the stream or do I have to manually process the array and insert the extra spaces manually at each line break detected? Seems like the string::right() manipulator is close: http://www.cplusplus.com/reference/iostream/manipulators/right/ Thanks. -William
This is the perfect situation to use a facet. A custom version of the codecvt facet can be imbued onto a stream. So your usage would look like this: int main() { /* Imbue std::cout before it is used */ std::ios::sync_with_stdio(false); std::cout.imbue(std::locale(std::locale::classic(), new IndentFacet())); std::cout << "Line 1\nLine 2\nLine 3\n"; /* You must imbue a file stream before it is opened. */ std::ofstream data; data.imbue(indentLocale); data.open("PLOP"); data << "Loki\nUses Locale\nTo do something silly\n"; } The definition of the facet is slightly complex. But the whole point is that somebody using the facet does not need to know anything about the formatting. The formatting is applied independent of how the stream is being used. #include <locale> #include <algorithm> #include <iostream> #include <fstream> class IndentFacet: public std::codecvt<char,char,std::mbstate_t> { public: explicit IndentFacet(size_t ref = 0): std::codecvt<char,char,std::mbstate_t>(ref) {} typedef std::codecvt_base::result result; typedef std::codecvt<char,char,std::mbstate_t> parent; typedef parent::intern_type intern_type; typedef parent::extern_type extern_type; typedef parent::state_type state_type; int& state(state_type& s) const {return *reinterpret_cast<int*>(&s);} protected: virtual result do_out(state_type& tabNeeded, const intern_type* rStart, const intern_type* rEnd, const intern_type*& rNewStart, extern_type* wStart, extern_type* wEnd, extern_type*& wNewStart) const { result res = std::codecvt_base::noconv; for(;(rStart < rEnd) && (wStart < wEnd);++rStart,++wStart) { // 0 indicates that the last character seen was a newline. // thus we will print a tab before it. Ignore it the next // character is also a newline if ((state(tabNeeded) == 0) && (*rStart != '\n')) { res = std::codecvt_base::ok; state(tabNeeded) = 1; *wStart = '\t'; ++wStart; if (wStart == wEnd) { res = std::codecvt_base::partial; break; } } // Copy the next character. *wStart = *rStart; // If the character copied was a '\n' mark that state if (*rStart == '\n') { state(tabNeeded) = 0; } } if (rStart != rEnd) { res = std::codecvt_base::partial; } rNewStart = rStart; wNewStart = wStart; return res; } // Override so the do_out() virtual function is called. virtual bool do_always_noconv() const throw() { return false; // Sometime we add extra tabs } }; See: Tom's notes below
1,391,756
1,391,772
What are some small, fast and lightweight open source applications (µTorrent -esque)?
Possible duplicate What is the best open source example of a lightweight Windows Application? µTorrent is a small bit-torrent client, a really small one. It doesn't come with an installer, just a exe, you drop in your PATH somewhere. It's super lightweight and yet feature rich. Plus it is the work of one man. It's also closed-source. Many people have been curious about how it has been written, and there are hints here and there about a custom library etc. But the question is, are there any programs with attributes like µTorrent that are available with source code--attributes like speed, small size, awesomeness. Possible related question (/questions/9603/what-is-some-great-source-code-to-read), but think smaller than something like the Linux kernel. Clarification: I don't want examples of bit-torrent source code, but anything which is used by tons of people (validation of awesomeness) and also fast, small and awesome!
I think you should take a look at Notepad++ if you want to see a feature-rich low-consumption of power software :)
1,391,869
1,392,016
Canny Edge Detector in C
I am looking for a bit of clarification on how the algorithms implemented in Canny edge detection - Wikipedia entry - work. It seems pretty straightforward to perform noise reduction using a 2D Gaussian filter, but I have heard that using two 1D filters - how is this accomplished? It's also simple to calculate the gradient and edge direction. However, when performing non-maximum suppression is there a neat trick to getting the rounded angle? What I'm currently doing is dividing the edge direction (theta) value by pi/4, casting it to an integer and using a switch statement. But, how does one handle the negative theta values - ie should -pi/4 be handled the same way as 3*pi/4 or the same as pi/4? Any advice/links are much appreciated! Thanks, Ben
Gauss distribution: [constants are omitted for simplicity] g2d(x,y)=exp(-xx-yy)=exp(-x^2) * exp(-y^2)=g1d(x) * g1d(y) Thus is can be separated into multiplication of 1d-distributions. And thus filtration can be done first in x-direction (independently on each row) and then in y-direction (independently on each column) rounded angle: If angle is outside of [0..pi) it's correct in this case to add/subtract pi as many times as needed (or use function fmod), and for [0..pi) all is clear. Also depending on platform it may be better to avoid arctan usage at all: you can draw a circle, divide it in 4 areas and produce a set of conditions for gradient components which use only arithmetic operations and give you answer in which area direction is.
1,392,195
1,392,222
How to get event when application is closed from task manager?
I have developed a Win32 application using C/C++, which runs on Vista and XP. I wanted to know, can I get any event in my application when my application is killed from task manager, by selecting the "end process" button? I want to free some memory on exit of my application.
Nope, your application is terminated without any notice. You are at mercy of Task Manager.
1,392,200
1,392,228
Sizeof string literal
The following code #include <iostream> using namespace std; int main() { const char* const foo = "f"; const char bar[] = "b"; cout << "sizeof(string literal) = " << sizeof( "f" ) << endl; cout << "sizeof(const char* const) = " << sizeof( foo ) << endl; cout << "sizeof(const char[]) = " << sizeof( bar ) << endl; } outputs sizeof(string literal) = 2 sizeof(const char* const) = 4 sizeof(const char[]) = 2 on a 32bit OS, compiled with GCC. Why does sizeof calculate the length of (the space needed for) the string literal ? Does the string literal have a different type (from char* or char[]) when given to sizeof ?
sizeof("f") must return 2, one for the 'f' and one for the terminating '\0'. sizeof(foo) returns 4 on a 32-bit machine and 8 on a 64-bit machine because foo is a pointer. sizeof(bar) returns 2 because bar is an array of two characters, the 'b' and the terminating '\0'. The string literal has the type 'array of size N of const char' where N includes the terminal null. Remember, arrays do not decay to pointers when passed to sizeof.
1,392,305
1,392,361
MSTest for huge legacy codebase
we have a huge codebase with about 1000k lines of native/unmanaged legacy c++ - code and we are going to provide the code with unit tests and MSTest would fit perfectly in our current development environment (TFS, VS 2010, ...). I know that MSTest is orginally meant to test managed code but its also possible to write unit tests for unmanaged sc. Are there any (later) drawbacks on the usage of MSTest for unmanaged code? Does anyone have any experience on this? The second opinion would be using Google.Test, but I would have to write a Visual Studio add-in to integrate the gtest framework in our environment. Thanks in advance!
I would not recommend MSTest for managed testing. See here for my experiences. However if you do insist I would say a really good way to test you legacy code would be use PInvoke interop to your c++ code.
1,392,315
1,392,387
Problems with Singleton Pattern
I've been reading about Singleton pattern for last few days. The general perception is that the scenarios where it is required are quite few (if not rare) probably because it has its own set of problems such as In a garbage collection environment it can be an issue with regards to memory management. In a multithreaded environment it can cause bottlenecks and introduce synchronization problems. Headache from testing prespective. I'm starting to get the ideas behind these issues but not totally sure about these concerns. Like in case of garbage collection issue, usage of static in singleton implementation (which is inherent to the pattern), is that the concern? Since it would mean that the static instance will last till the application. Is it something that degrades memory management (it just means that the memory allocated to the singleton pattern won't be freed)? Ofcourse in a multithreaded setup, having all the threads being in contention for the singleton instance would be a bottleneck. But how does usage of this pattern causes synchronization problems (surely we can use a mutex or something like that to synchronize access). From a (unit?)testing perspective, since singletons use static methods (which are difficult to be mocked or stubbed) they can cause problems. Not sure about this. Can someone please elaborate on this testing concern? Thanks.
In a garbage collection environment it can be an issue with regards to memory management In typical singleton implementations, once you create the singleton you can never destroy it. This non-destructive nature is sometimes acceptable when the singleton is small. However, if the singleton is massive, then you are unnecessarily using more memory than you should. This is a bigger issue in languages where you have a garbage collector (like Java, Python, etc) because the garbage collector will always believe that the singleton is necessary. In C++, you can cheat by delete-ing the pointer. However, this opens its own can of worms because it's supposed to be a singleton, but by deleting it, you are making it possible to create a second one. In most cases, this over-use of memory does not degrade memory performance, but it can be considered the same as a memory leak. With a large singleton, you are wasting memory on your user's computer or device. (You can run into memory fragmentation if you allocate a huge singleton, but this is usually a non-concern). In a multithreaded environment it can cause bottlenecks and introduce synchronization problems. If every thread is accessing the same object and you are using a mutex, each thread must wait until another has unlocked the singleton. And if the threads depend greatly upon the singleton, then you will degrade performance to a single-thread environment because a thread spends most of its life waiting. However, if your application domain allows it, you can create one object for each thread -- this way the thread does not spend time waiting and instead does the work. Headache from testing prespective. Notably, a singleton's constructor can only be tested once. You have to create an entirely new test suite in order to test the constructor again. This is fine if your constructor doesn't take any parameters, but once you accept a paremeter you can no longer effective unit teest. Further, you can't stub out the singleton as effectively and your use of mock objects becomes difficult to use (there are ways around this, but it's more trouble than it's worth). Keep reading for more on this... (And it leads to a bad design, too!) Singletons are also a sign of a poor design. Some programmers want to make their database class a singleton. "Our application will never use two databases," they typically think. But, there will come a time when it may make sense to use two databases, or unit testing you will want to use two different SQLite databases. If you used a singleton, you will have to make some serious changes to your application. But if you used regular objects from the start, you can take advantage of OOP to get your task done efficiently and on-time. Most cases of singleton's are the result of the programmer being lazy. They do not wish to pass around an object (eg, database object) to a bunch of methods, so they create a singleton that each method uses as an implicit parameter. But, this approach bites for the reasons above. Try to never use a singleton, if you can. Although they may seem like a good approach from the start, it usually always leads to poor design and hard to maintain code down the line.
1,392,422
1,392,684
Problems with bit-shifting in complicated expressions
I've distilled an equation down to this: speed = ( ( rear_wheel_speed_a + front_wheel_speed_a ) << 10 ) + ( ( rear_wheel_speed_b + front_wheel_speed_b ) << 2 ); but for some reason I'm getting unexpected results so I must be doing something wrong. This started out like this: speed = ((((rear_wheel_speed_a * 256 + rear_wheel_speed_b) / 16) + ((front_wheel_speed_a * 256 + front_wheel_speed_b) / 16)) / 2) * 128; That is the completely unsimplified version that does work. Are they not mathematically equivalents? all values are signed 16 bit integers. An example data set is: rear_wheel_speed_a = 0x03; rear_wheel_speed_b = 0x6F; //<-- I originally swapped front_wheel_speed_a = 0x02; //<-- these two values. Sorry! front_wheel_speed_b = 0xE2; That boils down to an answer of 6468. But in the first equation, my application behaves as though it is at least 3% smaller or larger. I say it like that because this is an embedded application where I have no way of confirming the outcome of the calculations other than to test if it is within a certain range of "normal". When I use the 2nd equation it falls within the parameters but with my "simplified" (bit shifted) equation it does not so I think I must be doing the shifts incorrectly (or I simplified wrong but I triple checked it). Any insight is appreciated, thank you.
From the second formula, I assume you operating 2 16bit values separated into their 8bit part a and b: rear_wheel_speed = 0x0302 front_wheel_speed = 0x6fe2 and the formula you using, can be simplified into speed=(front_speed+rear_speed)*4. From your values, 0x6fe2*4 just can fit 16bit, so this value can be evaluated in 16-bit arithmetic. But the values look like their parts are arranged wrong, and I have a feeling that real values are 0x036f and 0x02e2 (or 0x03ea and 0x026f) - those values are close to each other, as should be expected from speed of two wheels. Also it seems your formula is better, because it doesn't introduce loss of precision on divide operations. But keep in mind, that if you're using a good compiler (not always true for embedded applications) it usually converts divide/multiply to shifts itself when possible
1,392,494
1,403,236
Qt4 DNS Proxy QUdpSocket
I'm essentially trying to make a DNS proxy application using Qt4. If I set my DNS nameserver to 'localhost' then I want to forward all DNS requests to the server specified in the remoteSocket object. Everything seems to be working fine except sending the data from the remoteSocket object back to the localSocket object which is requesting the DNS lookup. When writing to localSocket, is there anything specific I need to know about that? The problem seems to be in readResponse(). #include "dns.h" Dns::Dns() { } void Dns::initSocket() { localDatagram = new QByteArray(); remoteDatagram = new QByteArray(); localSocket = new QUdpSocket(); connect(localSocket, SIGNAL(readyRead()), this, SLOT(readRequest()), Qt::DirectConnection); localSocket->bind(QHostAddress::LocalHost, 53); remoteSocket = new QUdpSocket(); remoteSocket->connectToHost(QHostAddress("4.2.2.1"), 53); connect(remoteSocket, SIGNAL(readyRead()), this, SLOT(readResponse()), Qt::DirectConnection); } void Dns::readRequest() { while (localSocket->hasPendingDatagrams()) { localDatagram->resize(localSocket->pendingDatagramSize());\ localSocket->readDatagram(localDatagram->data(), localDatagram->size()); remoteSocket->write(*localDatagram); } } void Dns::readResponse() { QByteArray bytes(remoteSocket->readAll()); qDebug() << "BYTES: [" << bytes.toBase64() << "]"; localSocket->write(bytes); }
I was assuming that using QUdpSocket::bind(), the resulting socket object would be able to obtain the peerAddress/peerPort using the access methods, however that was not the case. The final solution was to do: QHostAddress sender; quint16 senderPort; localSocket->readDatagram(localDatagram->data(), localDatagram->size(), &sender, &senderPort); And in readResponse(), localSocket->writeDatagram(bytes, sender, senderPort);
1,392,820
1,393,217
Why use ++i instead of i++ in cases where the value is not used anywhere else in the statement?
I'm well aware that in C++ int someValue = i++; array[i++] = otherValue; has different effect compared to int someValue = ++i; array[++i] = otherValue; but every once in a while I see statements with prefix increment in for-loops or just by their own: for( int i = 0; i < count; ++i ) { //do stuff } or for( int i = 0; i < count; ) { //do some stuff; if( condition ) { ++i; } else { i += 4; } } In the latter two cases the ++i looks like an attempt to produce smarty-looking code. Am I overseeing something? Is there a reason to use ++i instead of i++ in the latter two cases?
If we ignore force of habit, '++i' is a simpler operation conceptually: It simply adds one to the value of i, and then uses it. i++ on the other hand, is "take the original value of i, store it as a temporary, add one to i, and then return the temporary". It requires us to keep the old value around even after i has been updated. And as Konrad Rudolph showed, there can be performance costs to using i++ with user-defined types. So the question is, why not always just default to ++i? If you have no reason to use `i++´, why do it? Why would you default to the operation which is more complicated to reason about, and may be slower to execute?
1,392,863
1,420,261
Initializing qt resources embedded in static library
I have next situation: I need to create widget in standalone static library, which then will be linked with final application (visual c++ 9.0, qt 4.5). This static widget library contains some resources (icons), and consist of a several .cpp files (each contains standalone widget). As far as I know, i must initialize qt resource system, if i use them (resources) in static library, with call to "Q_INIT_RESOURCE( resource_file_name )". I solved this with next code (in every .cpp file in static library): #include <QAbstractButton> namespace { struct StaticLibInitializer { StaticLibInitializer() { Q_INIT_RESOURCE(qtwidgets_custom_resources); } }; StaticLibInitializer staticLibInitializer; } // ... widget code .... Instead of my first approach, I have created separate init.cpp file in static library project with initialization code (to avoid including initialization code in every .cpp file), but this didn't work. Why this didn't work ? Is this approach with StaticLibInitializer is safe and portable among various compilers and platforms ?
It didn't work because you managed to get hit by static initialization order fiasco. You can't move your code that initializes static objects outsize the translation unit (you can read it as source file) where these static objects are used. Not the way you did it. If you want to use the scheme you are using to initialize these static objects than move only declarations to your init.hpp header but leave instatiations StaticLibInitializer staticLibInitializer; in each file which uses static objects. Above advice assumes each widget uses only its own resources. If you have situation in which one widget's resources are used by another widget you run into static initialization order fiasco again. You can manage this situation by using code like this StaticLibInitializer { void initialize() { static Q_INIT_RESOURCE(qtwidgets_custom_resources); } StaticLibInitializer() { initialize(); } } to make sure multiply instantiations of StaticLibInitializer will initialize given resource only once and then instantiate StaticLibInitializer for every resource you are going to use in given translation unit.
1,393,006
1,396,629
How to get the cpu usage per thread on windows (win32)
Looking for Win32 API functions, C++ or Delphi sample code that tells me the CPU usage (percent and/or total CPU time) of a thread (not the total for a process). I have the thread ID. I know that Sysinternals Process Explorer can display this information, but I need this information inside my program.
With the help of RRUZ's answer above I finally came up with this code for Borland Delphi: const THREAD_TERMINATE = $0001; THREAD_SUSPEND_RESUME = $0002; THREAD_GET_CONTEXT = $0008; THREAD_SET_CONTEXT = $0010; THREAD_SET_INFORMATION = $0020; THREAD_QUERY_INFORMATION = $0040; THREAD_SET_THREAD_TOKEN = $0080; THREAD_IMPERSONATE = $0100; THREAD_DIRECT_IMPERSONATION = $0200; THREAD_SET_LIMITED_INFORMATION = $0400; THREAD_QUERY_LIMITED_INFORMATION = $0800; THREAD_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $03FF; function OpenThread(dwDesiredAccess: DWord; bInheritHandle: Bool; dwThreadId: DWord): DWord; stdcall; external 'kernel32.dll'; procedure TForm1.Button1Click(Sender: TObject); var iii:integer; handle:thandle; creationtime,exittime,kerneltime,usertime:filetime; begin Handle:=OpenThread(THREAD_SET_INFORMATION or THREAD_QUERY_INFORMATION, False, windows.GetCurrentThreadId); if handle<>0 then begin getthreadtimes(Handle,creationtime,exittime,kerneltime,usertime); label1.caption:='Total time for Thread #'+inttostr(windows.GetCurrentThreadId)+': '+inttostr( (int64(kerneltime)+int64(usertime)) div 1000 )+' msec'; CloseHandle(Handle); end; end;
1,393,065
1,394,257
Can I prevent invoking destructor before overloaded delete?
I'd like to use boost.pool. It's okay if you don't know about it. Basically, it has two main functions, malloc() and free(). I've overloaded new and delete for my custom defined class test. class test { public: test() { cout << "ctor" << endl; } ~test() { cout << "dtor" << endl; } void* operator new(size_t) throw() { cout << "custom operator new" << endl; return _pool.malloc(); } void operator delete(void* p) { cout << "custom operator delete" << endl; _pool.free(p); } void show() { cout << _i << endl; } private: int _i; static boost::pool<> _pool; };// class test boost::pool<> test::_pool(sizeof(test)); When I create instance of test using new, constructor was not called but if I delete it, destructor was called. Why? and can I avoid it?
Can't reproduce, when added #include <iostream> #include <boost/pool/pool.hpp> using namespace std; (why do people omit such things that are necessary to make the code compile?!) and int main() { test* p = new test; delete p; } This is either a stripped-down and modified version that doesn't have that behavior or your compiler may be broken (which version is it?) In any case your aim should be getting the constructor called, rather than getting destructor not called. Overloaded operator new just deals with raw memory allocation, the built-in new-expression should use that to obtain the memory and then call the constructor to create an instance there. Edit: the only way I can reproduce your output is by circumventing the built-in new-expression: test* p = static_cast<test*>(test::operator new(sizeof (test)));
1,393,074
1,393,184
Why people think that the only man who created C++ was Bjarne Stroustrup?
I am currently reading Stroustrup's book "Design and Evolution of C++" and it turns out that he was not the one who developed C++. When I hear someone saying "Bjarne Stroustrup developed C++ blah-blah-blah", I always feel it is very unfair to these guys who worked with BS - I mean Jonathan Shopiro, Andrew Koenig, Stan Lippman, Stefan Dewhurst and others. Why is it that way? Even wikipedia does not mention his team - only him What it that about? EDIT: When people say C#, they did not mean Anders Hejlsberg ONLY, there were a development team working on both exactly C# and .NET Framework. May be it`s because C++ does not belong to any software-giant company, as Java to Oracle or C# to Microsoft?
C++ has gone through two major stages of its evolution. The early days were Bjarne Stroustrup making a language. He obviously borrowed ideas from others, and solicited feedback from several clever language designers, and no doubt had a small team working under him, but the language was fundamentally his baby. In those days, I don't really have a problem with saying that Stroustrup designed the language. Obviously he didn't do it in a vacuum, he got a good deal of help from others, but that's just it. They helped him design his language. They didn't take ownership of it. The second phase is where it's at now: An ISO standard. These are maintained by committees, and in the C++ committee, Stroustrup is just one out of many participating members. His words might still carry a bit more weight because of his history with the language, but fundamentally, he no longer has any kind of special status. He's just a contributor, like all the others in the committee. The moment the language was standardized, it ceased to be "his" language. After that, he, and many others just helped the ISO maintain and evolve the language. At least that's how I see it.
1,393,454
1,393,547
Initialising an anonymous mutex-lock-holding class instance in the LHS of a comma operator
Suppose I have code something like this: #include "boost/thread/mutex.hpp" using boost::mutex; typedef mutex::scoped_lock lock; mutex mut1, mut2; void Func() { // ... } void test_raiicomma_1() { lock mut1_lock(mut1); Func(); } void test_raiicomma_2() { (lock(mut1)), Func(); } void test_raiicomma_3() { (lock(mut1)), (lock(mut2)), Func(); // Warning! } int main() { test_raiicomma_1(); test_raiicomma_2(); test_raiicomma_3(); return 0; } If the function test_raiicomma_1() were called from multiple threads, it locks a mutex to prevent any other thread also calling Func() at the same time. The mutex is locked when the variable mut1_lock is constructed, and released when it goes out of scope and is destructed. This works perfectly fine, but as a matter of style, needing to give a name to the temporary object holding the lock irked me. The function test_raiicomma_2() attempts to avoid this, by inialising the lock object and calling the function Func() within one expression. Is it correct that the temporary object destructor will not be called until the end of the expression, after Func() has returned? (If so, do you think it's ever worthwhile to use this idiom, or is it always clearer to declare the lock in a separate statement?) If the function test_raiicomma_3() needs to lock two mutexes, is it correct that the mutexes will be locked in order before calling Func(), and released afterwards, but may unfortunately be released in either order?
Is it correct that the temporary object destructor will not be called until the end of the expression, after Func() has returned? It is guaranteed that both constructor and destructor are called, as they have side effects, and that destruction will only happen at the end of a full expression. I believe it should work If the function test_raiicomma_3() needs to lock two mutexes, is it correct that the mutexes will be locked in order before calling Func(), and released afterwards, but may unfortunately be released in either order? Comma is always evaluated left to right, and automatic variables within a scope are always destroyed in reverse order of creation, so I think it's even guaranteed they are released in the (correct) order too As litb points out in the comments, you need braces or your expression will be parsed as a declaration. (If so, do you think it's ever worthwhile to use this idiom, or is it always clearer to declare the lock in a separate statement?) I don't think so no, to confusing for very, very little gain... I always use very explicit locks, and very explicit scopes (often extra {} within a block), decent threadsafe code is hard enough without 'special' code, and warrants very clear code in my opinion. YMMW of course :)
1,393,507
1,394,538
scope vs ctags in terms of features
I am a big fan of ctags Hence I am wondering if I have cscope, will I benefit more there two programs. Seems like the latter has the same features as ctags, namely, facilitating the finding of symbols. What are the features scope offers that can further increase my productivity with VIM? Thanks
cscope can certainly improve your productivity. ctags only allows you to navigate to the declaration of a symbol (one-way lookup). cscope allows you to: Go to the declaration of a symbol Show a selectable list of all references to a symbol Search for any global definition Functions called by a function Functions calling a function Search for a text string Search for a regular expression pattern Find a file Find all files including a file Tutorials: Vim/Cscope tutorial Using Vim and cscope within cygwin Related SO questions: cscope or ctags why choose one over the other? What is a good tool to aid in browsing/following C code? Vim+ctags tips and tricks
1,393,564
1,393,641
Get owner's access permissions using C++ and stat
How can I get the file owner's access permissions using stat from sys/stat.h using C++ in Kubuntu Linux? Currently, I get the type of file like this: struct stat results; stat(filename, &results); cout << "File type: "; if (S_ISDIR(results.st_mode)) cout << "Directory"; else if (S_ISREG(results.st_mode)) cout << "File"; else if (S_ISLNK(results.st_mode)) cout << "Symbolic link"; else cout << "File type not recognised"; cout << endl; I know I should use t_mode's file mode bits, but I don't know how. See sys/stat.h
struct stat results; stat(filename, &results); cout << "Permissions: "; if (results.st_mode & S_IRUSR) cout << "Read permission "; if (results.st_mode & S_IWUSR) cout << "Write permission "; if (results.st_mode & S_IXUSR) cout << "Exec permission"; cout << endl;
1,393,816
1,393,830
is it reasonable to program an algorithm without function calls?
I am programming an algorithm for a library and I didn't use function calls at all. The algorithm is about 100 lines and there is no duplicate code.or should I use inlining?
Is your algorithm readable? Maybe dividing it into several functions would be beneficial for readability (and hence maintainability) even if it will not reduce duplication.
1,393,898
1,395,340
How to add spin control to the dialog box using win32 C?
just want to know how to add an spin control ( in another name, up/down control ) in the dialog box using C program (win32 / code::block / mingw compiler)
Simplest way is by using a resource editor to design your dialog. Code::Blocks doesn't come with one, but ResEdit is one I've used. If you are editing an .rc file by hand, you'd add a line similar to the following within the dialog definition section: CONTROL "", IDC_SPIN1, UPDOWN_CLASS, UDS_ARROWKEYS, 7, 22, 11, 14 If you want to add it programatically, you can do so through the CreateWindow API function, e.g. HWND hwndUpDown = CreateWindow(UPDOWN_CLASS, NULL, WS_CHILD | WS_VISIBLE | UDS_ARROWKEYS, 7, 22, 11, 14, hwndDlg, NULL, hInst, NULL); where the hwndDlg parameter is the HWND of your dialog window. A good place to call this is when you handle the WM_INITDIALOG message for the dialog.
1,393,903
1,393,918
Why were references added to C++? (from the history viewpoint)
I've read many discussions on the difference between references and pointers and when to use which. They all seem to get their conclusions from analysis of the behaviors of the two. But I'd still like to know what was in the language designers' mind. What's the main motive for this design? In what typical situation is it intended to be used? Perhaps the answer is already included in the discussions I mentioned, but I want to know which are authentic. P.S. Does reference have a history as long as pointer in C++? Was it originated from the very beginning or came up as a patch for some situations? Thanks a lot.
Here's Stroustrup's reasons for adding them to the language. Basically they were mainly added to support operator overloading.
1,394,053
1,394,122
How to write a generic alert message using win32?
I just want to expand this following method into something more generic, which should accept any kind of argument and display it using MessageBox(): void alert(char *item) { MessageBox(NULL, item, "Message", MB_OK | MB_ICONINFORMATION); } Can anyone help?
#include <sstream> template<typename T> void alert(T item) { //this accepts all types that supports operator << std::ostringstream os; os << item; MessageBoxA(NULL, os.str().c_str(), "Message", MB_OK | MB_ICONINFORMATION); } //now you need specialization for wide char void alert(const wchar_t* item) { MessageBoxW(NULL, item, "Message", MB_OK | MB_ICONINFORMATION); }
1,394,132
7,166,199
macro and member function conflict
I have problem that,std::numeric_limits::min() conflicts with the "min" macro defined in "windef.h". Is there any way to resolve this conflict without undefine the "min" macro. The link below gives some hints, however I couldn't manage to use parenthesis with a static member function. What are some tricks I can use with macros? Thank you in advance.
The workaround is to use the parenthesis: int max = (std::numeric_limits<int>::max)(); It allows you to include the windef.h, doesn't require you to #undef max (which may have adverse side effects) and there is no need to #define NOMINMAX. Works like a charm!
1,394,229
1,394,287
Understanding return value optimization and returning temporaries - C++
Please consider the three functions. std::string get_a_string() { return "hello"; } std::string get_a_string1() { return std::string("hello"); } std::string get_a_string2() { std::string str("hello"); return str; } Will RVO be applied in all the three cases? Is it OK to return a temporary like in the above code? I believe it is OK since I am returning it by value rather than returning any reference to it. Any thoughts?
In two first cases RVO optimization will take place. RVO is old feature and most compilers supports it. The last case is so called NRVO (Named RVO). That's relatively new feature of C++. Standard allows, but doesn't require implementation of NRVO (as well as RVO), but some compilers supports it. You could read more about RVO in Item 20 of Scott Meyers book More Effective C++. 35 New Ways to Improve Your Programs and Designs. Here is a good article about NRVO in Visual C++ 2005.
1,394,370
1,394,398
What GNU make substitute do you recommend?
Imagine you're free to choose a tool like GNU make for a new C++ project. What would you choose? Are any usable substitutes out there? It shall have/be a command line interface "easy" to understand easy to set up for a default c++ project may support src/bin seperation as common for Java may not add too much dependencies to other software/libs platform independent (new) features: build rules / templates like make but in an human readable way recursively crawling directories and applying the rules if there is no other "Makefile" configuration by exception Note: Nothing's wrong with GNU make. I just don't like its grammar, all the stuff that grows in the years and the silly recursive make problems. I'm using gmake for years now.
I use cmake, and I'm very glad I made the switch. EDIT Feature list as found in the wikipedia article: Configuration files are CMake scripts, which use a programming language specialized to software builds Automatic dependency analysis built-in for C, C++, Fortran and Java Support of SWIG, Qt, via the CMake scripting language Built-in support for many versions of Microsoft Visual Studio including versions 6, 7, 7.1, 8.0, and 9.0 Generates build files for Eclipse CDT (C/C++ Development Tools) Detection of file content changes using traditional timestamps, Support for parallel builds Cross-compilation Global view of all dependencies, using CMake to output a graphviz diagram Support for cross-platform builds, and known to work on Linux and other POSIX systems (including AIX, *BSD systems, HP-UX, IRIX/SGI, and Solaris) Mac OS X Windows 95/98/NT/2000/XP, Windows Vista and MinGW/MSYS Integrated with DART (software), CDash, CTest and CPack, a collection of tools for software testing and release But to be honest: Just about anything is better than the gnu toolchain.
1,394,910
1,394,929
How to tame the Windows headers (useful defines)?
In one of the answers to this question jalf spoke about useful define NOMINMAX, that could prevent from unwanted defining min/max macros. Are there other useful defines that can help to control windows.h (or other Windows headers, for instance Microsoft C Runtime headers or STL implementation) behavior?
The most commonly used is probably WIN32_LEAN_AND_MEAN - it disables rarely used parts of the API. You can find more on MSDN's Using the Windows Headers. I remembered wrong about MSDN listing those defines, so here's list from windows.h: /* If defined, the following flags inhibit definition * of the indicated items. * * NOGDICAPMASKS - CC_*, LC_*, PC_*, CP_*, TC_*, RC_ * NOVIRTUALKEYCODES - VK_* * NOWINMESSAGES - WM_*, EM_*, LB_*, CB_* * NOWINSTYLES - WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_* * NOSYSMETRICS - SM_* * NOMENUS - MF_* * NOICONS - IDI_* * NOKEYSTATES - MK_* * NOSYSCOMMANDS - SC_* * NORASTEROPS - Binary and Tertiary raster ops * NOSHOWWINDOW - SW_* * OEMRESOURCE - OEM Resource values * NOATOM - Atom Manager routines * NOCLIPBOARD - Clipboard routines * NOCOLOR - Screen colors * NOCTLMGR - Control and Dialog routines * NODRAWTEXT - DrawText() and DT_* * NOGDI - All GDI defines and routines * NOKERNEL - All KERNEL defines and routines * NOUSER - All USER defines and routines * NONLS - All NLS defines and routines * NOMB - MB_* and MessageBox() * NOMEMMGR - GMEM_*, LMEM_*, GHND, LHND, associated routines * NOMETAFILE - typedef METAFILEPICT * NOMINMAX - Macros min(a,b) and max(a,b) * NOMSG - typedef MSG and associated routines * NOOPENFILE - OpenFile(), OemToAnsi, AnsiToOem, and OF_* * NOSCROLL - SB_* and scrolling routines * NOSERVICE - All Service Controller routines, SERVICE_ equates, etc. * NOSOUND - Sound driver routines * NOTEXTMETRIC - typedef TEXTMETRIC and associated routines * NOWH - SetWindowsHook and WH_* * NOWINOFFSETS - GWL_*, GCL_*, associated routines * NOCOMM - COMM driver routines * NOKANJI - Kanji support stuff. * NOHELP - Help engine interface. * NOPROFILER - Profiler interface. * NODEFERWINDOWPOS - DeferWindowPos routines * NOMCX - Modem Configuration Extensions */
1,394,912
1,394,924
Slot seemingly not recognized in Qt app
I have been working on learning C++ and Qt4 recently, but I have hit a stumbling block. I have the following class and implementation: class Window : public QWidget { public: Window(); public slots: void run(); private: //... }; and Window::Window() { //... connect(runBtn,SIGNAL(clicked()),this,SLOT(run())); //... } Window::run() { //... } However, when I attempt to build and run it, although it builds just fine, it immediately exits out with the message Object::connect: No such slot QWidget::run() Unless I did something wrong, Qt does not seem to be recognizing the slot run() Could anyone please help? Update: The code is now: class Window : public QWidget { Q_OBJECT public: Window(QWidget *parent = 0); public slots: void run(); private: //... }; and Window::Window(QWidget *parent) : QWidget(parent) { //... connect(runBtn,SIGNAL(clicked()),this,SLOT(run())); //... } Window::run() { //... } The program still "unexpectedly finished", but no longer tell me that there is no such thing as QWidget::run()
Possibly you have forgotten a Q_OBJECT macro in your Window class? class Window : public QWidget { Q_OBJECT public: Window() ...
1,395,004
1,395,051
Simple assembly questions
; int __stdcall wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd) _wWinMain@16 proc near var_4= dword ptr -4 hInstance= dword ptr 4 hPrevInstance= dword ptr 8 lpCmdLine= dword ptr 0Ch nShowCmd= dword ptr 10h From what I can see, the last 4 variables are the parameters passed to the WinMain function. Also, the var_4 must be a int variable I declared later in the function body. Now, I have a couple of questions: a) What is the size of a word on a 32bit windows program? 4 bytes? being a dword 8? b) Why is var_4 set to -4? Why not start at, let's say, 0? c) The standard procedure for defining ints in c is though var_x = dword ptr y? Thanks
a. DWORD is unsigned, 32 bit: see here (old name, MS started using it back when Windows was 16-bit). b. the top of stack (dword ptr 0) is taken up by the return-address c. a variable y here would not work. Anyway, this systematic use of dword ptr is characteristic of certain assemblers and disassemblers, not a "standard procedure".
1,395,202
1,395,287
Overriding "new" and Logging data about the caller
I'm trying to write a memory profiler and so far have been able to get my custom functions to work for malloc, free, new and delete. I tried using __FILE__ and __LINE__ to log the originator inside the overloaded new method, but (as expected) it just gives the details of where the overloaded function is. Is there a way to get the details about the originator to the overloaded functions without doing any changes to existing code of the component being tested (like #define for malloc)? The function I'm using is: void* operator new (size_t size) { if(b_MemProfStarted) { b_MemProfStarted = false; o_MemLogFile << "NEW: " << "| Caller: "<< __FILE__ << ":" << __LINE__ << endl; b_MemProfStarted = true; } void *p=malloc(size); if (p==0) // did malloc succeed? throw std::bad_alloc(); // ANSI/ISO compliant behavior return p; } The bool b_MemProfStarted is used to avoid recursive calls on ofstream and map.insert.
You can write new(foo, bar) MyClass; In this case the following function is called void*operator new(std::size_t, Foo, Bar){ ... } You can now call new(__LINE__, __FILE__) MyClass; and use the data with void*operator new(std::size_t, unsigned line, const char*file){ ... } Adding a macro #define new new(__LINE__, __FILE__) to the code being monitored will catch most invocations without needing source code changes. It's not perfect as you could call the operator new directly for example. In that case the preprocessor will turn your code into garbage. I know of no better way though.
1,395,361
1,395,398
manipulating LARGE_INTEGERS
I am converting some code from C to C++ in MS dev studio under win32. In the old code I was doing some high speed timings using QueryPerformanceCounter() and did a few manipulations on the __int64 values obtained, in particular a minus and a divide. But now under C++ I am forced to use LARGE_INTEGER because that's what QueryPerformanceCounter() returns. But now on the lines where I try and do some simple maths on the values I get an error: error C2676: binary '-' : 'LARGE_INTEGER' does not define this operator or a conversion to a type acceptable to the predefined operator I tried to cast the variables to __int64 but then get: error C2440: 'type cast' : cannot convert from 'LARGE_INTEGER' to '__int64' How do I resolve this? Thanks,
LARGE_INTEGER is a union of a 64-bit integer and a pair of 32-bit integers. If you want to perform 64-bit arithmetic on one you need to select the 64-bit int from inside the union. LARGE_INTEGER a = { 0 }; LARGE_INTEGER b = { 0 }; __int64 c = a.QuadPart - b.QuadPart;
1,395,395
1,395,422
Arrays inside structs in C
I´m struggling to understand this concept: I have a fixed size definition: (from http://msdn.microsoft.com/pt-br/library/aa931918.aspx) typedef struct _FlashRegion { REGION_TYPE regionType; DWORD dwStartPhysBlock; DWORD dwNumPhysBlocks; DWORD dwNumLogicalBlocks; DWORD dwSectorsPerBlock; DWORD dwBytesPerBlock; DWORD dwCompactBlocks; } FlashRegion, *PFlashRegion; this FlashRegion struct, is used in this another struct: (from: http://msdn.microsoft.com/pt-br/library/aa932688.aspx) typedef struct _FlashInfoEx { DWORD cbSize; FLASH_TYPEflashType; DWORD dwNumBlocks; WORD dwDataBytesPerSector; DWORD dwNumRegions; FlashRegion region[1]; } FlashInfoEx, *PFlashInfoEx; The problem is, I can have a variable number of FlashRegions inside a FlashInfoEx. The function that I´m debugging does this somewhere in the code: memcpy (pFlashInfoEx->region, g_pStorageDesc->pRegionTable, g_pStorageDesc->dwNumRegions * sizeof(FlashRegion)); That means that it copies an amount of regions to pFlashInfoEx (that I pass in the call of the function); So, the code will overwrite memory if dwNumRegions is bigger than one. If that is the case, Should I create a FlashRegion [FIXED_SIZE] in my code and somehow place/overwrite in FlashInfoEx->region? How do I do that? Thanks, Marcelo
The concept is while FlashRegion looks like a fixed size structure, it is actually dynamically sized. The magic is done when allocating the structure - instead of calling (FlashRegion*)malloc(sizeof(FlashInfoEx)) or new FlashRegion, you call something like (FlashRegion*)malloc(sizeof(FlashInfoEx)+sizeof(FlashRegion)*(numRegions-1))
1,395,396
1,395,460
error using restrict keyword
In the following example: void foo (double *ptr) { const double * restrict const restr_ptr=ptr; } I get this error: error: expected a ";" const double * restrict const restr_ptr=ptr; ^ I compile with -std=c99, using gcc 3.4 Any Ideas?
In C++, restrict is not a keyword (except for Microsoft extensions). It doesn't mean what it does in C. It looks as though you tried to apply C99 mode to your C++ compiler. Use a C compiler to compile C code, and use a C++ compiler to compile C++. Neither language is a subset of the other.
1,395,506
1,395,509
In c++ what does a tilde "~" before a function name signify?
template <class T> class Stack { public: Stack(int = 10) ; ~Stack() { delete [] stackPtr ; } //<--- What does the "~" signify? int push(const T&); int pop(T&) ; int isEmpty()const { return top == -1 ; } int isFull() const { return top == size - 1 ; } private: int size ; int top ; T* stackPtr ; } ;
It's the destructor, it destroys the instance, frees up memory, etc. etc. Here's a description from ibm.com: Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted. See https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_74/rzarg/cplr380.htm
1,395,601
1,395,727
What's the -complete- list of kinds of automatic type conversions a C++ compiler will do for a function argument?
Given a C++ function f(X x) where x is a variable of type X, and a variable y of type Y, what are all the automatic/implicit conversions the C++ compiler will perform on y so that the statement "f(y);" is legal code (no errors, no warnings)? For example: Pass Derived& to function taking Base& - ok Pass Base& to function Derived& - not ok without a cast Pass int to function taking long - ok, creates a temporary long Pass int& to function taking long& - NOT ok, taking reference to temporary Note how the built-in types have some quirks compared to classes: a Derived can be passed to function taking a Base (although it gets sliced), and an int can be passed to function taking a long, but you cannot pass an int& to a function taking a long&!! What's the complete list of cases that are always "ok" (don't need to use any cast to do it)? What it's for: I have a C++ script-binding library that lets you bind your C++ code and it will call C++ functions at runtime based on script expressions. Since expressions are evaluated at runtime, all the legal combinations of source types and function argument types that might need to be used in an expression have to be anticipated ahead of time and precompiled in the library so that they'll be usable at runtime. If I miss a legal combination, some reasonable expressions won't work in runtime expressions; if I accidently generate a combination that isn't legal C++, my library just won't compile. Edit (narrowing the question): Thanks, all of your answers are actually pretty helpful. I knew the answer was complicated, but it sounds like I've only seen the tip of the iceberg. Let me rephrase the question a little then to limit its scope then: I will let the user specify a list of "BaseClasses" and a list of "UserDefinedConversions". For Bases, I'll generate everything including reference and pointer conversions. But what cases (const/reference/pointer) can I safely do from the UserDefined Conversions list? (The user will give bare types, I will decorate with *, &, const, etc. in the template.)
Note how the built-in types have some quirks compared to classes: a Derived can be passed to function taking a Base (although it gets sliced), and an int can be passed to function taking a long, but you cannot pass an int& to a function taking a long&!! That's not a quirk of built-in vs. class types. It's a quirk of inheritance. If you had classes A and B, and B had a conversion to A (either because A has a constructor taking B, or because B has a conversion operator to A), then they'd behave just like int and long in this respect - conversion can occur where a function takes a value, but not where it takes a non-const reference. In both cases the problem is that there is no object to which the necessary non-const reference can be taken: a long& can't refer to an int, and an A& can't refer to a B, and no non-const reference can refer to a temporary. The reason the base/derived example doesn't encounter this problem because a non-const Base reference can refer to a Derived object. The fact that the types are user-defined is a necessary but not a sufficient condition for the reference to be legal. Convertible user-defined classes where there is no inheritance behave just like built-ins. This comment is way too long for comments, so I've used an answer. It doesn't actually answer your question, though, other than to distinguish between: "Conversions" where a reference to a derived class is passed to a function taking a reference to a base class. Conversions where a user-defined or built-in conversion actually creates an object, such as from int to long.
1,395,715
1,395,988
Should const functionality be expanded?
EDIT: this question could probably use a more apropos title. Feel free to suggest one in the comments. In using C++ with a large class set I once came upon a situation where const became a hassle, not because of its functionality, but because it's got a very simplistic definition. Its applicability to an integer or string is obvious, but for more complicated classes there are often multiple properties that could be modified independently of one another. I imagine many people forced to learn what the mutable keyword does might have had similar frustrations. The most apparent example to me would be a matrix class, representing a 3D transform. A matrix will represent both a translation and a rotation each of which can be changed without modifying the other. Imagine the following class and functions with the hypothetical addition of 'multi-property const'. class Matrix { void translate(const Vector & translation) const("rotation"); void rotate(const Quaternion & rotation) const("translation"); } public void spin180(const("translation") & Matrix matrix); public void moveToOrigin(const("rotation") & Matrix matrix); Or imagine predefined const keywords like "_comparable" which allow you to define functions that modify the object at will as long as you promise not to change anything that would affect the sort order of the object, easing the use of objects in sorted containers. What would be some of the pros and cons of this kind of functionality? Can you imagine a practical use for it in your code? Is there a good approach to achieving this kind of functionality with the current const keyword functionality? Bear in mind I know such a language feature could easily be abused. The same can be said of many C++ language features Like const I would expect this to be a strictly compile-time bit of functionality. If you already think const is the stupidest thing since sliced mud, I'll take it as read that you feel the same way about this. No need to post, thanks. EDIT: In response to SBK's comment about member markup, I would suggest that you don't have any. For classes / members marked const, it works exactly as it always has. For anything marked const("foo") it treats all the members as mutable unless otherwise marked, leaving it up to the class author to ensure that his functions work as advertised. Besides, in a matrix represented as a 2D array internally, you can't mark the individual fields as const or non-const for translation or rotation because all the degrees of freedom are inside a single variable declaration.
Scott Meyers was working on a system of expanding the language with arbitary constraints (using templates). So you could say a function/method was Verified,ThreadSafe (etc or any other constraints you liked). Then such constrained functions could only call other functions which had at least (or more) constraints. (eg a method maked ThreadSafe could only call another method marked ThreadSafe (unless the coder explicitly cast away that constraint). Here is the article: http://www.artima.com/cppsource/codefeatures.html The cool concept I liked was that the constraints were enforced at compile time.
1,396,050
1,396,169
use gtk_signal_connect with a member function in c++
What's the best way to connect a GTK+ signal to a non-static member function? I have a GUI class in c++ that uses gtk, and i want do something like this: Gui::Gui () { gtk_signal_connect(GTK_OBJECT(somObject), "clicked", GTK_SIGNAL_FUNC( &(this->ClickHandler) ), NULL); } void Gui::ClickHandler(GtkWidget *w, gpointer data) { // handle the click } I know this doesn't work b/c the GTK_SIGNAL_FUNC can't point to a member function unless it's a static function, so what's the best way to do this? Is it possible to use a single proxy handler function and boost::bind somehow? Here is what I tried: gtk_signal_connect(GTK_OBJECT(somObject), "clicked", GTK_SIGNAL_FUNC( SigHandler ), boost::bind( &(Gui::ClickHandler), this) ); void SigHandler(GtkWidget *w, gpointer data) { data(w); } void Gui::ClickHandler(GtkWidget *w) { // handle the click } here's the error: gui.cc: error: 'data' cannot be used as a function
I assume your class contains some internal data that the signal handler needs access to. If not, just use a static function for the signal handler. Otherwise, here are a couple of ideas: Create a sigc++ or boost functor out of the member function; set it as the data passed to the signal handler. Use a generic signal handler that just calls the functor. During construction, register each instance of the class somewhere and use a signal handler that calls the member function for each registered instance.
1,396,107
1,397,356
C++: Status and control pattern
I'm writing a C++ background/server application for Linux/Windows. Is there a standard control/profiling/reporting service I should use to expose my application's current status in a standardized way? If not, what's a good pattern (or library) to use for exposing this kind of data and control? Specifically, I want to expose the following data: Relative "usage" of "components" (where usage/components is user-defined) Any errors/faults Memory, CPU, other misc process data Method/class execution profile Average time spent in method/class Total calls I want to expose the following control mechanisms Start, stop, restart, reload X... (commandesque control) Parameter tuning
Many Linux systems now have dbus for this sort of stuff. Daemons run and provide information and a control interface on the system bus. Desktop applications communicate with one another via the session bus. For instance, the bluez bluetoothd daemon uses dbus to provide information about bluetooth devices and services, and a control interface to control those devices. NetworkManager also uses dbus for status and control purposes. However, starting and stopping are functions that are usually outside the actual application itself. Perhaps the correct architecture would be for some service supervision framework (upstart, runit...) to provide a dbus interface to control services. That said, dbus itself can be used to start services on demand, but it really is not meant for service supervision. See this for more. Edit: I've just been reading about upstart some more, and it does have a dbus interface for job control. It is subject to change however.
1,396,265
1,396,331
Defining a variable inside c++ inline assembly
Let's say we have the following c++ code: int var1; __asm { mov var1, 2; } Now, what I'd like to know is if I didn't want to define var1 outside the __asm directive, what would I have to do to put it inside it. Is it even possible? Thanks
To do that, you'll need to create a "naked" method with _declspec(naked) and to write yourself the prolog and the epilog that are normally created by the compiler. The aim of a prolog is to: set up EBP and ESP reserve space on stack for local variables save registers that should be modified in the body of the function An epilog has to: restore the saved register values clean up the reserved space for local variables Here is a standard prolog push ebp ; Save ebp mov ebp, esp ; Set stack frame pointer sub esp, localbytes ; Allocate space for locals push <registers> ; Save registers and a standard epilog: pop <registers> ; Restore registers mov esp, ebp ; Restore stack pointer pop ebp ; Restore ebp ret ; Return from function Your local variables will then begin at (ebp - 4) and go downward to (ebp - 4 - localbytes). The function parameters will start at (ebp + 8) and go upward.
1,396,267
1,407,137
OleInitialize fails when Common Lanuage Runtime is enabled?
I am working on a wxWidgets console application that I want to call into = a C# DLL from, via the CLR. Unfortunately, the application hiccups in the wxWidgets application initialization code because OleInitialize is failing. The error I'm seeing is a pop-up simply stating "Cannot initialize OLE." It seems that this problem is usually avoided by setting the apartment style for threads by applying a directive to the application's entry point but I'm really struggling with what entry point I'm looking for. My C# code is a DLL: there's no specific entry point. The code compiled with /CLR exists in a .lib which is linked into my wxWidgets application. wxWidgets actually defines the WinMain in their code, and allows me to override behaviors via implementing wxApp. Other suggestions include disabling OLE support in wxWidgets but In my release, 2.8.6, setting wxUSE_OLE, wxUSE_CLIPBOARD, wxUSE_DATAOBJ, wxUSE_DRAG_AND_DROP to 0 creates unresolved externals while compiling wxWidgets. Has enjoy encountered this before and found an effective work around? Can anyone provide any clarification on what entry point I need to be modifying?
As mentioned in my question, this is a problem involving the thread style settings between the C++ application and the CLR defaults. This was apparently a bug, once upon a time, and Microsoft has released a fix: http://msdn.microsoft.com/en-us/library/s6bz81ya.aspx Recompiling the executable the uses the CLR-enabled .lib with /CLRTHREADATTRIBUTE:STA was sufficient to eliminate the errors I was seeing.
1,396,340
1,396,344
What does the "|" in "int style = SWT.APPLICATION_MODAL | SWT.OK;" do (and how to Google it)?
I can't search for | in Google. If you had found it in a software source code that you are trying to interpret, you didn't know what it does and you couldn't ask other people for help, how would you find out what it does?
The pipe operator in this case means "use both SWT.APPLICATION_MODAL and SWT.OK as options/flags for my popup box." It's a very commonly used idiom with bitfield configuration identifiers, esp. in windowing systems like SWT or Win32. How it works The pipe (|) operator is the bitwise OR operator, that is, it computes an OR operation of the two binary integer values. If you check out where APPLICATION_MODAL and OK are defined, you'll find they are something like this: ... SWT.OK = 1, // 00000001 in binary SWT.ABORT_RETRY_IGNORE = 2, // 00000010 in binary SWT.OK_CANCEL = 4; // 00000100 in binary ... SWT.APPLICATION_MODAL = 32; // 00100000 in binary ... (and so on...) When you bitwise OR two (or more) of these numbers together, individual bits will be set for each of the options: int style = SWT.OK | SWT.APPLICATION_MODAL = 00000001 | 00100000 = 00100001 The windowing toolkit that goes to interpret style will be able to tell exactly what you wanted (a popup box that is Modal and has an OK button) by doing a bitwise AND like this: ... if(style & SWT.OK) { // we want an OK box } if(style & SWT.ABORT_RETRY_IGNORE) { // we want an Abort/Retry/Ignore box } if(style & SWT.OK_CANCEL) { // we want an OK/Cancel box } ... if(style & SWT.APPLICATION_MODAL) { // We want a modal box } ... Kinda clever, in my humble opinion. It allows you to select/represent multiple configuration options in a single variable. The trick is in the integer definitions of the options, and ensuring that they are only powers of 2.
1,396,397
1,396,595
Build Boost-powered solution in VS
Boost rocks, it is great and extremely powerful, but I hate it everytime I build solution in my Visual Studio 7.1. It seems Boost has impact on build time (not positive). I cannot remove all Boost usage from my project to compare build times but I tried it on small projects and the difference is meaningful. I guess the problem is that Boost consists of thousands of header files which include themselves very extensively. So, when I include, say, boost/function.hpp into my header file, it may lead to including hundred of Boost headers. Is there someone who experienced the same? Any ideas how to solve it? Rough thoughts: Add boost to precompiled headers? At least they will be parsed and kept in one file Do explicit instantination for some Boost templates? Prepare Boost headers somehow? Do not include Boost to header files (sounds unreal) ... PS. Yep, Boost also uses hardcore templating that pretty hard to compiler I guess, so thousands of header files are not the only problem.
Naturally, including boost leads to longer compilations times - just like including any library does. Being (mostly) a template library offcourse leads to quite big performance penalty as all of the logic is implemented in the headers. I've had good results including (a subset of) boost in precompiled headers. However, I belive that the gain is greatest with MSVC 9. On MSVC 7 I have seen several reports saying that precompiled headers of templates frequently leads to performance penalty. Another crucial aspect determining if you'll see performance gain is to include the appropiate headers in the precompiled header. Only include headers you frequently use, and make sure they are never changed (that is, think three times before including your own headers here) I do not know if explicit instantination has any effect, even though I doubt it. If anyone has seen any results on this (regardless compiler), it would be very interesting. "Preparing" boost headers sounds like altering them which sounds like a very bad idea to me. You don't want to end up maintaining customized headers... May not be so unreal as you might think. Always use as many forward declarations as possible to reduce the "footprint" of each header file. Consider using the Pimpl pattern to avoid including boost headers that are not reflected in the public interface of your class (offtopic: I consider Pimpl to often be unnecessary. Instead I try to slice the classes into smaller pieces, acheiving the same result in a "cleaner" fashion). Don't be afraid to include general, common classes (e.g. shared_ptr) as long as you're consistent in the usage of these classes (if your using them in all your classes you wont see much gain in hiding them away from one header). Upgrading MSVC (to support parallel builds) will help. However, this is always an issue in C++. To minimize the problem, you need to be very strict and follow guidelines to reduce the footprint of your headers. Now and then you should look through the include-clauses and make sure there are nothing unnecessary included. If you're list of includes done in the header is getting long you're probably doing something wrong - most includes should only be in the cpp.
1,396,458
1,402,325
Confusing function lookup with templates in C++
Starting with the following (using gcc version 4.0.1): namespace name { template <typename T> void foo(const T& t) { bar(t); } template <typename T> void bar(const T& t) { baz(t); } void baz(int) { std::cout << "baz(int)\n"; } } If I add (in the global namespace) struct test {}; void bar(const test&) { std::cout << "bar(const test&)\n"; } then, as I expected, name::foo(test()); // produces "bar(const test&)" But if I just add void bar(const double&) { std::cout << "bar(const double&)\n"; } it can't seem to find this overload: name::foo(5.0) // produces "baz(int)" What's more, typedef std::vector<int> Vec; void bar(const Vec&) { std::cout << "bar(const Vec&)\n"; } doesn't appear either, so name::foo(Vec()); gives a compiler error error: cannot convert ‘const std::vector<int, std::allocator<int> >’ to ‘int’ for argument ‘1’ to ‘void name::baz(int)’ Is this how the lookup is supposed to work? (Note: if I remove the namespace name, then everything works as I expected.) How can I modify this example so that any overload for bar is considered? (I thought that overloads were supposed to be considered before templates?)
I assume you added the double version to the global namespace too, and you call foo from main after everything is defined. So this is basically two phase name lookup. Looking up an unqualified function name that is dependent because an argument in the call is dependent (on its type) is done in two phases. The first phase does a unqualified and argument dependent lookup in the definition context. It then freezes the result, and using the instantiation context (the sum of the declarations at the point of instantiation) does a second argument dependent lookup only. No unqualified lookup is done anymore. So for your example it means: The call bar(t) within foo<test> looks up bar using argument dependent lookup at the instantiation context (it doesn't find it using unqualified lookup, because foo is declared above the bar template). Depending on whether you define the global bar before or after the foo template, it will find the global bar declaration using argument dependent lookup already in the first phase (it's defined in test's namespace). Then the call in main will instantiate foo<test> and it will possible find bar in this phase (if you declared it after you declared the template). The call bar(t) within foo<int> doesn't do argument dependent lookup (or rather, the result for the lookup is an empty declaration set), because int is a fundamental type. So, unqualified lookup at the definition context will find nothing either, because the matching bar template is declared after the foo template. The call would be ill-formed, and the standard says about this situation at 14.6.4.2/1 If the call would be ill-formed [...] then the program has undefined behavior. You should therefor consider this as a "i did a dirty thing and the compiler chose not to slap me" case, i think :) The call bar(t) within foo<Vec> will do the lookups again, and will look for bar in std:: (because that's where std::vector is defined). It doesn't find a bar there, neither in the definition context. So it decides to go by undefined behavior again, and uses the bar template, and which in itself again does undefined behavior by using the baz declared after it and which cannot be found by neither ADL nor unqualified lookup from the definition context. If the vector were a vector<test>, then lookup for bar would be done at global scope too, because argument dependent lookup will not only use the argument type directly, but also the type of the template arguments in them, if there are any. If you use GCC, then don't rely entirely on its behavior. In the following code, it claims the call is ambiguous, although the code is perfectly fine - the f in afake should not be a candidate. namespace aname { struct A { }; void f(A) { } } namespace afake { template<typename T> void g(T t) { f(t); } void f(aname::A) { } } int main() { aname::A a; afake::g(a); } If you want to test your snippets against conformance, best use the comeau online compiler with the strict settings.
1,396,691
1,396,733
Programmatically get amount of RAM installed on OS X
I'm working on a machine that has 8 gigs of memory installed and I'm trying to programmatically determine how much memory is installed in the machine. I've already attempted using sysctlbyname() to get the amount of memory installed, however it seems to be limited to returning a signed 32 bit integer. uint64_t total = 0; size_t size = sizeof(total); if( !sysctlbyname("hw.physmem", &total, &size, NULL, 0) ) m_totalMemory = total; The above code, no matter what type is passed to sysctlbyname, always returns 2147483648 in the total variable. I've been searching through IOKit and IORegistryExplorer for another route of determining installed memory, but have come up with nothing so far. I've found IODeviceTree:/memory in IORegistryExplorer, but there's no field in there for size. I'm not finding anything anywhere else in the IO Registry either. Is there a way to access this information via IOKit, or a way to make sysctlbyname return more than a 32-bit signed integer?
You can use sysctl() and query HW_MEMSIZE.This returns the memory size as a 64-bit integer, instead of the default 32-bit integer. The man page gives the details.
1,396,942
1,396,988
Efficient computation of the high order bits of a 32 bit integer multiplication
Many CPUs have single assembly opcodes for returning the high order bits of a 32 bit integer multiplication. Normally multiplying two 32 bit integers produces a 64 bit result, but this is truncated to the low 32 bits if you store it in a 32 bit integer. For example, on PowerPC, the mulhw opcode returns the high 32 bits of the 64 bit result of a 32x32 bit multiply in one clock. This is exactly what I'm looking for, but more portably. There's a similar opcode, umulhi(), in NVidia CUDA. In C/C++, is there an efficient way to return the high order bits of the 32x32 multiply? Currently I compute it by casting to 64 bits, something like: unsigned int umulhi32(unsigned int x, unsigned int y) { unsigned long long xx=x; xx*=y; return (unsigned int)(xx>>32); } but this is over 11 times slower than a regular 32 by 32 multiply because I'm using overkill 64 bit math even for the multiply. Is there a faster way to compute the high order bits? This is clearly not best solved with a BigInteger library (which is overkill and will have huge overhead). SSE seems to have PMULHUW, a 16x16 -> top 16 bit version of this, but not a 32x32 -> top 32 version like I'm looking for.
gcc 4.3.2, with -O1 optimisation or higher, translated your function exactly as you showed it to IA32 assembly like this: umulhi32: pushl %ebp movl %esp, %ebp movl 12(%ebp), %eax mull 8(%ebp) movl %edx, %eax popl %ebp ret Which is just doing a single 32 bit mull and putting the high 32 bits of the result (from %edx) into the return value. That's what you wanted, right? Sounds like you just need to turn up the optimisation on your compiler ;) It's possible you could push the compiler in the right direction by eliminating the intermediate variable: unsigned int umulhi32(unsigned int x, unsigned int y) { return (unsigned int)(((unsigned long long)x * y)>>32); }
1,397,004
1,397,017
Better seeds than time(0)?
I understand that time(0) is commonly using for seeding random number generators and that it only becomes a problem when the program is being run more than once per second. I'm wondering what are some better seeds to consider when generating random numbers. I read about GetTickCount, timeGetTime, and QueryPerformanceCounter on Windows. Will these suffice for almost all operations or are there even better seeding options? Here is a quick code example using the boost library: #include <iostream> #include <boost/random.hpp> using namespace std; using namespace boost; int main() { mt19937 randGen(42); uniform_int<> range(0,100); variate_generator<mt19937&, uniform_int<> > GetRand(randGen, range); for (int i = 0; i < 30; ++i) cout << GetRand() << endl; }
Some early hacks of Netscape security centered around knowing when an encrypted packet was sent and narrowing down the possible range of seeds with that knowledge. So, getting a tick count or something else even remotely deterministic is not your best bet. Even using a seed, the sequence of "random" numbers is deterministic based on that seed. A Nevada Gaming Commission investigator realized this about certain slots he was supposed to inspect and used that knowledge to earn quite a bit of money before being caught. If you need world-class randomness, you can add hardware to your system that provides for a highly randomized number. That's how the well-known poker sites do it (at least, that's what they say). Short of that, combine a number of factors from your system that all change independently and rapidly, with as little predictability as possible, to create a very decent seed. An answer to a related post on SO suggested using Guid.NewGuid().GetHashCode(). Since a Guid is based on a number of deterministic factors including the time, that does not form a good basis for a seed: Cryptanalysis of the WinAPI GUID generator shows that, since the sequence of V4 GUIDs is pseudo-random, given the initial state one can predict up to the next 250 000 GUIDs returned by the function UuidCreate[2]. This is why GUIDs should not be used in cryptography, e.g., as random keys. Source: Wikipedia Globally Unique Identifier
1,397,110
1,401,069
How to overload operators with Boost.Python
I am trying to overload operators of a C++ class using Boost.Python. According to this, I am doing it the right way... but I have a bunch of compiler errors. Here is a simple example I made trying to pinpoint the problem: #include "boost/python.hpp" using namespace boost::python; class number { public: number(int i) : m_Number(i) { } number operator+(int i) { return number(m_Number + i); } private: int m_Number; }; BOOST_PYTHON_MODULE(test) { class_<number>("number", init<int>()) .def(self() + int()); } Here are the compiler errors: Error 1 error C2064: term does not evaluate to a function taking 0 arguments c:\users\kevin\documents\visual studio 2008\projects\boostpythontest\boostpythontest\test.cpp 16 BoostPythonTest Error 2 error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,Fn,const A1 &,const A2 &,const A3 &)' : expects 5 arguments - 1 provided c:\users\kevin\documents\visual studio 2008\projects\boostpythontest\boostpythontest\test.cpp 16 BoostPythonTest Error 3 error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,Fn,const A1 &,const A2 &)' : expects 4 arguments - 1 provided c:\users\kevin\documents\visual studio 2008\projects\boostpythontest\boostpythontest\test.cpp 16 BoostPythonTest Error 4 error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,A1,const A2 &)' : expects 3 arguments - 1 provided c:\users\kevin\documents\visual studio 2008\projects\boostpythontest\boostpythontest\test.cpp 16 BoostPythonTest Error 5 error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,F)' : expects 2 arguments - 1 provided c:\users\kevin\documents\visual studio 2008\projects\boostpythontest\boostpythontest\test.cpp 16 BoostPythonTest Am I missing something here ? Thanks
I've not used boost.python, but your errors look like there are some incompatible arguments when some template magic tries to bind something to something else. So I looked at the link you provided, and found one major difference: class_<X>("X") .def(self + int()) vs yours class_<number>("number", init<int>()) .def(self() + int()); I guess, self and self() could do that.
1,397,190
1,397,219
Visual C++ Precompiled Headers errors
Update: What are the effects of including stdafx.h in my header files? I started on a C++ project in Linux/Eclipse CDT and imported it into Visual C++/Windows. In Visual C++, I started using precompiled headers to speed up compilation and defined stdafx.cpp and stdafx.h. Here's my stdafx.h #pragma once #include <string> #include <vector> #include <map> ... and my stdafx.cpp #include "stdafx.h" In every .h and .cpp file, I have the following: #pragma once //if in a header file #include "stdafx.h" For both release and debug, I have "Create Precompiled Header (/Yc)". It compiled fine in debug mode, but in release mode it keeps reporting error LNK2005: ___@@_PchSym_@00@UfhvihUaszlaDUwlxfnvmghUnnlUhixUnnlPeDUnnlPeDUivovzhvUvmgrgbOlyq@ already defined in A.obj If I switch both to "Use precompiled header", I get in both Debug and Release fatal error C1854: cannot overwrite information formed during creation of the precompiled header in object file: Does anyone know what's going on?
You put "create precompiled header" only for stdafx.cpp. Then "use precompiled header" for all of the other ".cpp" files. Finally, have include "stdafx.h" at the start of each ".cpp" file (not usually in the header files.
1,397,313
1,397,343
Programmatically get Google search results
How can I get Google search results from inside a program? I need to get an array of search results for a specified string.
C++ requires a little more work then other languages. You will need to connect to Google's REST Search API and then use a JSON parser to parse out the search results. Json.org has a collection of JSON parsers in various languages.
1,397,484
1,401,533
Custom text color for certain indexes in QTreeView
I would like to draw texts in one of the columns in a QTreeView widget using a custom color (depending on the data related to each row). I tried to overload the drawRow() protected method and change the style option parameter like this (a stripped-down example): virtual void drawRow(QPainter* p_painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItem optionCustom = option; if (index.column() == 2) { optionCustom.palette.setColor(QPalette::Text, Qt::red); } QTreeView::drawRow(p_painter, optionCustom, index); } But obviously I am missing something because this does not seem to work (I tried to change also the QPalette::WindowText color role).
In your model, extend the data() function to return a given color as the Qt::ForegroundRole role. For example: virtual QVariant MyModel::data( const QModelIndex &index, int role ) const { if ( index.isValid() && role == Qt::ForegroundRole ) { if ( index.column() == 2 ) { return QVariant( QColor( Qt::red ) ); } return QVariant( QColor( Qt::black ) ); } return QAbstractItemModel::data( index, role ); }
1,397,490
1,397,508
Implementing std::list item read/write events
I'm new to c++ but have set my mind on a specific task that needs me to enable adding a specific chunk of code to be execute whenever any list item is attempted to be changed or read. The resulting list should behave and look as much as as possible to std::list except for this small exception that would enable me to execute a specific tasks whenever this list is about to be read/written to. From what i have found out so far, all i could think of is deriving a class from list::iterator and overloading it's operator* and operator= to implement these specific tasks. Then i should derive a class from std::list and make it use my new iterator type by overloading begin() and end() methods. Or is there a better way of making it use a custom iterator? That would handle the iterator access but I can see lists can even return pointers to it's members. I guess there is nothing i can do about them and will have to remove this feature from my new list class. I would appreciate your oppinion on this subject.
Deriving from std::list is almost certainly not the answer. The collections in stl are simply not meant to be derived from and doing so will cause you problems down the road. The classic example of why is the destructor problem. The destructors in stl collections are not virtual. This will break any logic you place in your derived class destructor if an object is deleted via a reference to the std::list. For example std::list* pList = new YourNewListClass(); delet pList; // runs std::list::~list() You'd also need to override much more than the methods on the iterator. It would require changing every method which can possibly mutate the collection. A more stable approach would be to implement your own std::list style class which follows the standard stl container behavior. You could then include use this list in the places you wanted events without running into the problems with deriving from std::list.
1,397,678
1,397,689
C pointer array scope and function calls
I have this situation: { float foo[10]; for (int i = 0; i < 10; i++) { foo[i] = 1.0f; } object.function1(foo); // stores the float pointer to a const void* member of object } object.function2(); // uses the stored void pointer Are the contents of the float pointer unknown in the second function call? It seems that I get weird results when I run my program. But if I declare the float foo[10] to be const and initialize it in the declaration, I get correct results. Why is this happening?
For the first question, yes using foo once it goes out of scope is incorrect. I'm not sure if it's defined behavior in the spec or not but it's definitely incorrect to do so. Best case scenario is that your program will immediately crash. As for the second question, why does making it const work? This is an artifact of implementation. Likely what's happenning is the data is being written out to the data section of the DLL and hence is valid for the life of the program. The original sample instead puts the data on the stack where it has a much shorter lifetime. The code is still wrong, it just happens to work.
1,397,737
1,397,766
How to get the digits of a number without converting it to a string/ char array?
How do I get what the digits of a number are in C++ without converting it to strings or character arrays?
The following prints the digits in order of ascending significance (i.e. units, then tens, etc.): do { int digit = n % 10; putchar('0' + digit); n /= 10; } while (n > 0);
1,397,862
1,398,063
is there any database transaction mechanism in MFC/C++?
I want to make sure that if any error occurs during the database processing phase, program will know it need to roll back the whole process. any good ORM in MFC/C++ for doing this ?
The MFC _ConnectionPtr object has BeginTrans, CommitTrans and RollbackTrans methods. http://msdn.microsoft.com/en-us/library/ms675942(VS.85).aspx I wouldn't call it good though, you'd need to wrap it.
1,397,924
1,398,378
Get original SQL query from prepared statement in SQLite
I'm using SQLite (3.6.4) from a C++ application (using the standard C api). My question is: once a query has been prepared, using sqlite3_prepare_v2(), and bound with parameters using sqlite3_bind_xyz() - is there any way to get a string containing the original SQL query? The reason is when something goes wrong, I'd like to print the query (for debugging - this is an in-house developer only test app). Example: sqlite3_prepare_v2(db, "SELECT * FROM xyz WHERE something = ? AND somethingelse = ?", -1, &myQuery, NULL); sqlite3_bind_text(myQuery, 1, mySomething); sqlite3_bind_text(myQuery, 2, mySomethingElse); // .... // somewhere else, in another function perhaps if (sqlite3_step(myQuery) != SQLITE_OK) { // Here i'd like to print the actual query that failed - but I // only have the myQuery variable exit(-1); } Bonus points if it could also print out the actual parameters that was bound. :)
As per the comments in sqlite3.c (amalgamation), sqlite3_sql(myQuery) will return the original SQL text. I don't see any function for finding the value bound at a particular index, but we can easily add one to the standard set of SQLite functions. It may look something like this: const char* sqlite3_bound_value(sqlite3_stmt* pStmt, int index) { Vdbe *p = (Vdbe *)pStmt; // check if &p->aVar[index - 1] points to a valid location. return (char*)sqlite3ValueText(&p->aVar[index - 1], SQLITE_UTF8); } Well, the above code shows only a possible way sqlite3_bound_value() could be implemented. I haven't tested it, it might be wrong, but it gives certain hints on how/where to start.
1,398,234
1,398,282
How to save and load a C++ application state in a modular way
I have a distributed C++ application, which is composed of 4 processes spread on 2 machines. One of the applications serves as "control center" for the rest of the applications. I want to be able to save the current state to a file and load it again later. What exactly is a "state" is defined separately by each module in the system. When saving, the modules states should be combined to one file. When loading, each module should read the state data back from the file. The state has to be saved to a human-readable text file, as it is going to be edited by some users. So a binary file format is not an option. In addition, a standard file format such as XML or YAML is preferred. How would you recommend implement a basic framework for state saving/loading as I just described? I prefer to do the minimum data serialization work needed for this task. Also, the framework should allow to easily add more data to be saved in the future.
Have a look at the boost.Serialize lib. It's a very nice lib for (un)streaming objects to an (xml) file. Instead of writing a Load and Save function your class only need to write a serialize function and this function will work both ways. class X { friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & make_nvp("degrees(=xml_tagname)", degrees); ar & make_nvp("minutes(=xml_tagname)", minutes);; ar & BOOST_SERIALIZATION_NVP(seconds); // =auto xml tag } }
1,398,274
1,398,374
How to reconstruct a data-structure from injected process' memory space?
I've got this DLL I made. It's injected to another process. Inside the other process, I do a search from it's memory space with the following function: void MyDump(const void *m, unsigned int n) { const char *p = reinterpret_cast(m); for (unsigned int i = 0; i < n; ++i) { // Do something with p[i]... } } Now my question. If the target process uses a data structure, let's say struct S { unsigned char a; unsigned char b; unsigned char c; }; Is it always presented the same way in the process' memory? I mean, if S.a = 2 (which always follows b = 3, c = 4), is the structure presented in a continuous row in the process' memory space, like Offset --------------------- 0x0000 | 0x02 0x03 0x04 Or can those variables be in a different places there, like Offset --------------------- 0x0000 | 0x00 0x02 0x00 0x03fc | 0x00 0x03 0x04 If the latter one, how to reconstruct the data-structure from various points from the memory? Many thanks in advance, nhaa123
If your victim is written in C or C++, and the datatypes used are truly that simple, then you'll always find them as a single block of bytes in memory. But as soon as you have C++ types like std::string that observation no longer holds. For starters, the exact layout will differ between C++ compilers, and even different versions of the same compiler. The bytes of a std::string will likely not be in a contiguous array, but sometimes they are. If they're split in two, finding the second half probably will not help you in finding the first half. Not throw in more complicated environments like a JIT'ting JVM running a Java app. The types you encounter in memory are very very complex; one could write a book about decoding them.
1,398,331
1,398,366
How do I implement a "single instance"-like design?
I'm writing an application which will run as a daemon. UIs will connect to it over TCP. Now, there is a class called UiTcpInterface which will handle all communication between the UI and this daemon. Now, I'm faced with the problem of ensuring there is only one instance of UiTcpInterface. What would be the best way to do it? Currently, I've thought of two ways: This is the classic singleton pattern: make the constructor private, and provide a static instance() method to the class UiTcpInterface Implement all functionality as static members of UiTcpInterface. The main method will make sure that all initialization is done. Which of these two should I follow? Can you please give me a pro-con list of the two methods? Thanks :)
This has been discussed many, many times. Singleton - Why use classes? Problems with Singleton Pattern Why choose a static class over a singleton implementation? https://stackoverflow.com/questions/1304647/static-storage-vs-singleton-why-people-prefer-singleton-closed
1,398,436
1,398,525
C++ interview - testing potential candidates
I have to interview some C++ candidates over the next few weeks and as the most senior programmer in the company I'm expected to try and figure out whether these people know what they are doing. So has anybody got any suggestions? Personally I hate being left in a room to fill out some C++ questions so I'd rather do a more complex test that I can chat with the interviewee about their approaches and so forth as we go along. ie it doesn't matter whether they get the right answers or not its how they approach the problem that interests me. I don't care whether they understand obscure features of the language but I do care that they have a good solid understanding of pointers as well as understanding the under lying differences between pointers and references. I would also love to see how they approach optimisation of a given problem because solid fast code is a must, in my opinion. So any suggestions along these lines would be greatly appreciated!
I wouldn't make them write code. Instead, I'd give them a couple of code snippets to review. For example, the first would be about design by contract: See if they know what preconditions, postconditions and invariants are. Do a couple of small mistakes, such as never initializing an integer field but asserting that it is >= 0 in the invariant, and see if they spot them. The second would be to give them bool contains(char * inString, char c). Implement it with a trivial loop. Then ask whether there are any mistakes. Of course, your code here does not check for null in the input parameter inString (even if the very previous question talked about preconditions!). Also, the loop finishes at character 0. Of course, the candidate should spot the possible problems and insist on using std::string instead of this char * crap. It's important because if they do complain, you'll know that they won't add their own char *'s to new code. An alternative which addresses containers: give them a std::vector<int> and code which searches for prime numbers or counts the odd numbers or something. Make some small mistake. See if they find any issues and they understand the code. Ask in which situation a std::set would be better (when you are going to search elements quite systematically and original order of entrance doesn't matter.). Discuss everything live, letting them think a couple minutes. Capture the essence of what they say. Don't focus on "coverage" (how many things they spot) because some people may be stressed. Listen to what they actually say, and see if it makes any sense. I disagree with writing code in interviews. I'd never ask anyone to write code. I know my handwritten code would probably suck in a situation like that. Actually, I have seldom been asked to do so, but when I have, I haven't been hired.
1,398,445
1,398,594
Directory structure for a C++ library
I am working on a C++ library. Ultimately, I would like to make it publicly available for multiple platforms (Linux and Windows at least), along with some examples and Python bindings. Work is progressing nicely, but at the moment the project is quite messy, built solely in and for Visual C++ and not multi-platform at all. Therefore, I feel a cleanup is in order. The first thing I'd like to improve is the project's directory structure. I'd like to create a structure that is suitable for the Automake tools to allow easy compilation on multiple platforms, but I've never used these before. Since I'll still be doing (most of the) coding in Visual Studio, I'll need somewhere to keep my Visual Studio project and solution files as well. I tried to google for terms like "C++ library directory structure", but nothing useful seems to come up. I found some very basic guidelines, but no crystal clear solutions. While looking at some open source libraries, I came up with the following: \mylib \mylib <source files, read somewhere to avoid 'src' directory> \include? or just mix .cpp and .h \bin <compiled examples, where to put the sources?> \python <Python bindings stuff> \lib <compiled library> \projects <VC++ project files, .sln goes in project root?> \include? README AUTHORS ... I have no/little previous experience with multi-platform development/open source projects and am quite amazed that I cannot find any good guidelines on how to structure such a project. How should one generally structure such a library project? What ca be recommended to read? Are there some good examples?
One thing that's very common among Unix libraries is that they are organized such that: ./ Makefile and configure scripts. ./src General sources ./include Header files that expose the public interface and are to be installed ./lib Library build directory ./bin Tools build directory ./tools Tools sources ./test Test suites that should be run during a `make test` It somewhat reflects the traditional Unix filesystem under /usr where: /usr/src Sometimes contains sources for installed programs /usr/include Default include directory /usr/lib Standard library install path /usr/share/projectname Contains files specific to the project. Of course, these may end up in /usr/local (which is the default install prefix for GNU autoconf), and they may not adhere to this structure at all. There's no hard-and-fast rule. I personally don't organize things this way. (I avoid using a ./src/ directory at all except for the largest projects, for example. I also don't use autotools, preferring instead CMake.) My suggestion to you is that you should choose a directory layout that makes sense for you (and your team). Do whatever is most sensible for your chosen development environment, build tools, and source control.
1,398,763
1,399,160
Delphi PChar to C++ const char*
I am trying to use a C++ dll from a native program. I am following the virtual method scenario as explained here Lets say my C++ function signature is of the form int Setup(const char* szIp, const char* szPort); And the corresponding delphi signature is function Setup(ip, port: PChar):Integer: virtual; cdecl; abstract; And somewhere from the delphi program i can call pObj.Setup('192.168.1.100', '97777'); The control comes into the dll, but szIp and szPort formal parameters only receives the first character of the ip and port that I had passed from the delphi program. I understand that it has to do with null terminating the string properly in delphi. So i had tried the following too. var pzIp, pzPort: PChar; szIp, szPort: string; begin szIp := '192.168.1.2'; szPort := '9777'; //initilize memory for pchar vars GetMem(pzIp, Length(szIp)+1); GetMem(pzPort, Length(szPort)+1); //null terminate the strings pzIp[Length(szIp)+1] := #0; pzPort[Length(szPort)+1] := #0; //copy strings to pchar StrPCopy(pzIp, szIp); StrPCopy(pzPort, szPort); end. This a'int working either. When i Writeln pzIp and pzPort I get strange results. Forgot to tell, all member functions from the C++ dll are compiled with __stdcall and exported properly
In Delphi 2010 (and Delphi 2009) the "char" type is actually a WIDEChar - that is, 16 bits wide. So when you call your C++ function, if that is expecting CHAR to be 8 bits wide (so called "ANSI", rather than UNICODE), then it is going to misinterpret the input parameter. e.g. if you pass the string 'ABC'#0 (I'm showing the null terminator explicitly but this is just an implicit part of a string in Delphi and does not need to be added specifically) this passes a pointer to an 8 byte sequence, NOT 4 bytes! But because the 3 characters in your string have only 8-bit code-point values (in Unicode terms, this means that what the C++ code "sees" is a string that looks like: 'A'#0'B'#0'C'#0#0#0 Which would explain why your C++ code seems only to be getting the first character of the string - it is seeing the #0 in the 2nd byte of that first character and assuming that it is the null terminator for the entire string. You either need to modify your C++ code to correctly receive pointers to WideChar strings, OR modify the function signature in Delphi and convert your strings to ANSIString in the Delphi code before passing those to the C++ function: Revised function signature: function Setup(ip, port: PANSIChar):Integer: virtual; stdcall; abstract; and the corresponding "Long hand" showing conversion of strings to ANSIString before calling the function - the compiler may take care of this for you but you might find it helpful to make it clear in your code rather than relying on "compiler magic": var sIPAddress: ANSIString; sPort: ANSIString; begin sIPAddress := '192.168.1.100'; sPort := '97777'; pObj.Setup(sIPAddress, sPort); // etc...
1,398,837
1,399,619
Programmatically launch sfx archive on Windows 7 (using _execv)? (C++)
My (MS Windows) application can update itself over the internet by download a self extracting archive and launching it via _execv (C++). Now while launching the sfx archive works fine on Windows XP, it doesn't on Windows 7. I guess it has to do with UAC, but even turning UAC off didn't cure this problem. The downloaded sfx archive has the same owner and full access rights as other executables on my computer I can run via _execv. What do I have to do to make this work?
Windows 7 is able to detect installers based on file name and file content and requires additional privilege to start such files. As far as I know Administrator has no such additional privilege. Try to use ShellExecuteEx with runas parameter. It should show you dialog with request for permission to start installer.
1,398,843
1,561,223
Service Control Security Issues in XPCOM
I'm am developing a Firefox extension which interfaces with an underlying Windows service (which I have already made). During the development so far I encountered one bug in the installer program (which installs the FF extension AND the service). This was due to the security model on Vista requiring elevated privileges to be able to install and start the service. I adjusted the installer and now it installs fine (just with additional Vista'esque warning dialogs being displayed to end-users - which I can live with !) I am now in the process of developing an XPCOM component that will install along with the XUL stuff I have already made. There will be a XUL javascript interface to the XPCOM which will try to do things like stop and start the service (e.g when user-configuration data is changed). My question: Since FF will normally be run under a user account, will I run into any difficulties on Vista or other Windows flavors trying to start or stop my own service via XPCOM? (When users run the installer I don't mind security dialogs popping up in Vista. But I certainly don't want this to happen whenever they try to change their info in the XUL interface.) What is the correct way to go about this?
Yes, if your service is running as an Administrator then the Firefox process, running as a normal user will not be able to start or stop it. However, it appears that you can use the "sc" command to set access controls on your service from your installer, which means you can allow non-admin users to start and stop your service. You'll need to use "sc sdset", which is documented (lightly) here: http://technet.microsoft.com/en-us/library/cc742037%28WS.10%29.aspx However, to use that, you'll need to read up on the "Security Descriptor Definition Language", which looks kind of complicated: http://msdn.microsoft.com/en-us/library/aa379567%28VS.85%29.aspx This blog entry appears to have some human-readable information on it: http://blogs.dirteam.com/blogs/jorge/archive/2008/03/26/parsing-sddl-strings.aspx
1,398,855
1,398,877
Which one will be faster
Just calculating sum of two arrays with slight modification in code int main() { int a[10000]={0}; //initialize something int b[10000]={0}; //initialize something int sumA=0, sumB=0; for(int i=0; i<10000; i++) { sumA += a[i]; sumB += b[i]; } printf("%d %d",sumA,sumB); } OR int main() { int a[10000]={0}; //initialize something int b[10000]={0}; //initialize something int sumA=0, sumB=0; for(int i=0; i<10000; i++) { sumA += a[i]; } for(int i=0; i<10000; i++) { sumB += b[i]; } printf("%d %d",sumA,sumB); } Which code will be faster.
There is only one way to know, and that is to test and measure. You need to work out where your bottleneck is (cpu, memory bandwidth etc). The size of the data in your array (int's in your example) would affect the result, as this would have an impact into the use of the processor cache. Often, you will find example 2 is faster, which basically means your memory bandwidth is the limiting factor (example 2 will access memory in a more efficient way).
1,399,051
1,399,120
WNDPROC declaration problem, converting from C to C++
I am converting a program from C to C++. I have the compiler set to use the __fastcall calling convention by default. I used to have a declaration line as follows: INT32 PASCAL graph_window_handler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) Later I have: wndclass.lpfnWndProc = graph_window_handler; This all compiled and worked under C. But under C++ I get all sorts of complaints form the compiler about the second line of code. I guess I need to change the original declaration to something involving WNDPROC, perhaps with a _cdecl thrown in? With or without the INT32? but it seems that every variation I try still gets complained about. What should the declaration look like such that the second line does not get complained about? - cheers.
According to MSDN documentation it should look like the following: LRESULT CALLBACK graph_window_handler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); And if you'll check WinUser.h you'll see that WNDPROC typedef'ed as follows: typedef LRESULT (CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM);
1,399,062
1,400,034
Making my GUI accessible through keyboard (Xp, Visual Studio, C++)
I've built a GUI with button, groups of buttons, edits, listboxes... etc... but now I want to know how to make my gui accessible through keyboard, I mean, changing the focus by pressing tab button. Does anybody have any idea on how to do this? I'm using Windows Xp and the GUI is writen on C++ using Visual Studio 2008. Thanks a lot UPDATE: INT APIENTRY _tWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; INITCOMMONCONTROLSEX ics; ics.dwSize = sizeof(ics); ics.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&ics); // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_PRUEBA, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDA_ACCEL_TABLE)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if ((!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) && (!IsDialogMessage(msg.hwnd, &msg))) //if ((!IsDialogMessage(msg.hwnd, &msg)) & (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg) )) //if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } I have a lot of controls in my GUI, should I put WS_TABSTOP in all of them? What if I have a group of buttons... should I put WS_TABSTOP in every button and in the group? only in the individual buttons? For example I'll paste a group I've created: INT CrearControles(HWND hwnd, LPARAM lParam) { HINSTANCE hInstance; HFONT hfont; HWND hctrl; int i; hInstance = ((LPCREATESTRUCT)lParam)->hInstance; hfont = (HFONT)GetStockObject( DEFAULT_GUI_FONT ); /* Insertar controles */ hctrl = CreateWindowEx( 0, "BUTTON", /* Nombre de la clase */ "Rol", /* Texto del título */ BS_GROUPBOX | WS_CHILD | WS_VISIBLE | WS_GROUP , /* Estilo */ 20, 15, /* Posición */ 180, 100, /* Tamaño */ hwnd, /* Ventana padre */ (HMENU)GRUPO_ROL,/* Identificador del control */ hInstance, /* Instancia */ NULL); /* Sin datos de creación de ventana */ SendMessage(hctrl, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE, 0)); hctrl = CreateWindowEx(0, "BUTTON", "Receptor", BS_NOTIFY | BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 30, 35, 70, 25, hwnd, (HMENU)BOTON_RECEPTOR, hInstance, NULL); SendMessage(hctrl, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE, 0)); SendDlgItemMessage(hwnd, BOTON_RECEPTOR, BM_SETCHECK, BST_CHECKED, 0); SetFocus(hctrl); hctrl = CreateWindowEx(0, "BUTTON", "Emisor", BS_NOTIFY | BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 30, 65, 70, 25, hwnd, (HMENU)BOTON_EMISOR, hInstance, NULL); SendMessage(hctrl, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE, 0)); hctrl = CreateWindowEx(0, "STATIC", "Telefono", SS_SIMPLE | WS_CHILD | WS_VISIBLE, 150, 55, 100, 55, hwnd, (HMENU)LABEL_TELEFONO, hInstance, NULL); SendMessage(hctrl, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE, 0)); SetFocus(hctrl); hctrl = CreateWindowEx(0, "EDIT", "", ES_READONLY | ES_LEFT | WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_NUMBER , 115, 68, 80, 20, hwnd, (HMENU)EDIT_TELEFONO, hInstance, NULL); SendMessage(hctrl, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE, 0)); SetFocus(hctrl); return 1; } Thx
If you're GUI is running as a standard modal dialog you should get tabbing and Alt key navigation between controls for free. ie: controls with the WS_TABSTOP style set you should be able to tab to, controls with short cut key defined (eg: a button with a caption of "&Do Something" should be accessible with Alt+D - and the D should be displayed underlined). If your window is not running as standard modal dialog, to get this behaviour your message loop needs to call IsDialogMessage before dispatching each message. eg: MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { if (!IsDialogMessage(m_hWndYourWindow, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
1,399,063
1,399,076
C++ #define preprocessor
I need to know that does the #define directive in C++ declares global label? By global I mean visible in every file? I'm using Visual Studio 2008, (guess if that matters)
No, only in the current translation unit. I.e. every file which has #define, or includes a file that has the #define will see the definition. Edit, to respond to your comment: to get a define in every file, either put it in a header which gets included everywhere, or use some compiler option to get defines added. e.g. for gcc one would do gcc -Dthedefine=itsvalue Not sure how one specifies such includes in VC++, but I'm sure it's possible somehow.
1,399,215
1,399,292
Difference between _declspec and __declspec?
I sometimes see keywords starting with two underscores and other times just one. Is there any difference?
I believe that _declspec is older name of the same Microsoft specific keyword __declspec. From a C++ Standard point of view, two underscores are more correct than a single underscore for an extension like this. That's according to 17.4.3.1.2/1: Certain sets of names and function signatures are always reserved to the implementation: Each name that contains a double underscore (_ _) or begins with an underscore followed by an upper- case letter (2.11) is reserved to the implementation for any use. Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
1,399,275
1,399,356
Simplifying FOR loops
I have a function that essentially reads values in from a vector of doubles, appends these to a string (while ensuring a space between each and setting their precisions) and returns the end result, minus the final whitespace: std::string MultiplePrintProperties::GetHpitchString() { std::string str; vector< double >::iterator it; for ( it = Vals.begin(); it != Vals.end(); it++ ) { ostringstream s; // Set precision to 3 digits after the decimal point // and read into the string boost::format fmt( "%.3f " ); s << fmt % *( it ); str.append( s.str() ); } // Remove last white space and return string return str.substr( 0, str.length() - 1 ); } I would like to find out if this code could be simplified in any way. I have recently been investigating the use of for_each and functors in particular but have not been able to figure out how these techniques could improve this particular example.
Since you're actually transforming doubles into strings, and appending these strings to a stringstream, you can use std::transform for that: // your functor, transforming a double into a string struct transform_one_double { std::string operator()( const double& d ) const { boost::format fmt( "%.3f " ); return (fmt % d).str(); } }; // iteration code, taking each value and inserting the transformed // value into the stringstream. std::transform( vals.begin(), vals.end() , std::ostream_iterator<std::string>( s, " ") , transform_one_double() );
1,399,492
1,402,431
Image warp with VTK?
I'd like to warp a vtkImageData with a vector field, similar to what itk's WarpImageFilter does. the vtkGridTransform object seems promising, but there doesn't seem to be a vtkTransformImageFilter... Is what I want to do at all possible with VTK? Thanks a lot!
Ok, here's the answer: The filter for applying a transform to an image is vtkImageReslice, and the relevant example is Hybrid/Testing/Tcl/TestGridWarp3D.tcl. The basics of deformable transformations in VTK are described in the following paper: "Generalized 3D nonlinear transformations for medical imaging: an object-oriented implementation in VTK" David G. Gobbi, Terry M. Peters Computerized Medical Imaging and Graphics July 2003 (Vol. 27, Issue 4, Pages 255-265) Source: http://vtk.1045678.n5.nabble.com/Image-Warp-with-VTK-td1247962.html
1,399,666
1,399,697
Attaching char buffer to vector<char> in STL
What is the correct (and efficient) way of attaching the contents of C buffer (char *) to the end of std::vector<char>?
When you have a vector<char> available, you're probably best calling the vector<char>::insert method: std::vector<char> vec; const char* values="values"; const char* end = values + strlen( values ); vec.insert( vec.end(), values, end ); Delegating it to the vector is to be preferred to using a back_inserter because the vector can then decide upon its final size. The back_inserter will only push_back, possibly causing more reallocations.
1,399,669
1,399,943
How to link graphviz with VIsual C++
Someone please tell me How to link graphviz( or call its code) in C++ (VIsual Studio)
Graphviz has a documentation Using Graphviz as a library. Is that what are you searching for? Just in case, here described how to use libraries in Visual C++.
1,399,692
1,399,728
w8004 compiler warning BDS6 c/c++
It is a best practise to initialise a variable at the time of declaration. int TMyClass::GetValue() { int vStatus = OK; // A function returns a value vStatus = DoSomeThingAndReturnErrorCode(); if(!vStatus) //Do something else return(vStatus); } In the debug mode, a statement like this int vStatus = OK; is causing no issues during DEBUG MODE build. The same when build in RELEASE MODE, throws a warning saying: w8004: 'vStatus' is assigned a value that is never used. Also, i am using the same variable further down my code with in the same function,like this if(!vStatus)and also I return the value of return(vStatus); When I looked at the web for pointers on this debug Vs Release, compilers expect you to initialise your variable at the time of declaring it. I am using Borland developer studio 6 with windows 2003 server. Any pointers will help me to understand this issue. Thanks Raj
You initialise vStatus to OK, then you immediately assign a new value. Instead of doing that you should initalise vStatus with a value that you're going to use. Try doing the following instead: int TMyClass::GetValue() { // A function returns a value int vStatus = DoSomeThingAndReturnErrorCode(); if(!vStatus) //Do something else return(vStatus); } Edit: Some clarification. Initialising a variable, only to never use that value, and then to assign another value to the variable is inefficient. In your case, where you're just using int's it's not really a problem. However, if there's a large overhead in creating / copying / assignment for your types then the overhead can be a performance drain, especially if you do it a lot. Basically, the compiler is trying to help you out and point out areas in your program where improvements can be made to your code
1,399,891
1,399,985
c++ vector<char> and sockets
Is there a way to call send / recv passing in a vector ? What would be a good practice to buffer socket data in c++ ? For ex: read until \r\n or until an upper_bound ( 4096 bytes )
std::vector<char> b(100); send(z,&b[0],b.size(),0); Edit: I second Ben Hymers' and me22's comments. Also, see this answer for a generic implementation that doesn't try to access the first element in an empty vectors.
1,400,660
1,400,673
What is a common C/C++ macro to determine the size of a structure member?
In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent: typedef struct myStruct { int x[10]; int y; } myStruct_t; const size_t sizeof_MyStruct_x = sizeof(myStruct_t.x); // error For reference, this should be how to find the size of 'x' if you first define a dummy variable: myStruct_t dummyStructVar; const size_t sizeof_MyStruct_x = sizeof(dummyStructVar.x); However, I'm hoping to avoid having to create a dummy variable just to get the size of 'x'. I think there's a clever way to recast 0 as a myStruct_t to help find the size of member variable 'x', but it's been long enough that I've forgotten the details, and can't seem to get a good Google search on this. Do you know? Thanks!
In C++ (which is what the tags say), your "dummy variable" code can be replaced with: sizeof myStruct_t().x; No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression. This works in C, and in C++ is better because it also works for classes without an accessible no-args constructor: sizeof ((myStruct_t *)0)->x
1,400,787
1,702,677
getting an error of "Service not found" in a async_resolve handler
I have code that looks like the following: //unrelated code snipped resolver.reset(new tcp::resolver(iosvc)); tcp::resolver::query query(host, port); resolver->async_resolve(query, boost::bind(&TCPTransport::handle_resolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); LOG4CXX_INFO(logger, "Attempting connection to at " << host << ":" << port); //unrelated code snipped void TCPTransport::handle_resolve(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { if (err) { LOG4CXX_ERROR(logger, "Error: " << err.message()); } else { tcp::endpoint endpoint = *endpoint_iterator; if (!socket) { socket.reset(new tcp::socket(iosvc)); } socket->async_connect(endpoint, boost::bind(&TCPTransport::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator)); } } When I run this code, with the appropriate gate and port of the server I know is up an running, I get the following text in my log file: Error: Service not found Can anyone provide some insight into what this error actually means?
In Boost it looks like that error can only happen as a result of a call to getaddrinfo(). In MSDN (for what it's worth), it sounds like the service name (or port) isn't supported for the types of socket that the caller (ASIO?) supports. In other words, it seems like you're attempting a TCP connection on either a non-TCP socket (not likely, since you're using TCP classes for your DNS resolution) or to a non-TCP port (not sure what to do about that). I recommend stepping into the code using a debugger to see what is going wrong, though that will be a lot easier if you use a synchronous call to resolve(). Otherwise you'll have to set multiple breakpoints on the various internal handlers that ASIO uses (not that bad, but still a nuisance). Hope that helps...
1,400,856
1,400,884
I can't understand this line - dereferencing an address of private member variable or what?
I asked a question while ago about accessing the underlying container of STL adapters. I got a very helpful answer: template <class T, class S, class C> S& Container(priority_queue<T, S, C>& q) { struct HackedQueue : private priority_queue<T, S, C> { static S& Container(priority_queue<T, S, C>& q) { return q.*&HackedQueue::c; } }; return HackedQueue::Container(q); } int main() { priority_queue<SomeClass> pq; vector<SomeClass> &tasks = Container(pq); return 0; } Unfortunately, I couldn't understand this line: return q.*&HackedQueue::c; What does this line do? Also, how could that line access the private container in priority_queue that is passed to the function Container?
Think of it like this: (q).*(&HackedQueue::c); First, you have HackedQueue::c, which is just the name of a member variable. Then you take &HackedQueue::c, which is a pointer to that member variable. Next you take q, which is just an object reference. Then you use the "bind pointer to member by reference" operator .* to bind the member variable referred to by the member-variable pointer using q as the this. As to the private member issue, priority_queue::c is only protected, not private, so it should come as no surprise that when you derive from priority_queue, that you can access its protected members.
1,400,954
1,400,970
How does this C++ code compile without an end return statement?
I came across the following code that compiles fine (using Visual Studio 2005): SomeObject SomeClass::getSomeThing() { for each (SomeObject something in someMemberCollection) { if ( something.data == 0 ) { return something; } } // No return statement here } Why does this compile if there is no return statement at the end of the method?
This is to support backwards compatibility with C which did not strictly require a return from all functions. In those cases you were simply left with whatever the last value in the return position (stack or register). If this is compiling without warning though you likely don't have your error level set high enough. Most compilers will warn about this now.
1,401,342
1,406,385
Why is linker optimization so poor?
Recently, a coworker pointed out to me that compiling everything into a single file created much more efficient code than compiling separate object files - even with link time optimization turned on. In addition, the total compile time for the project went down significantly. Given that one of the primary reasons for using C++ is code efficiency, this was surprising to me. Clearly, when the archiver/linker makes a library out of object files, or links them into an executable, even simple optimizations are penalized. In the example below, trivial inlining costs 1.8% in performance when done by the linker instead of the compiler. It seems like compiler technology should be advanced enough to handle fairly common situations like this, but it isn't happening. Here is a simple example using Visual Studio 2008: #include <cstdlib> #include <iostream> #include <boost/timer.hpp> using namespace std; int foo(int x); int foo2(int x) { return x++; } int main(int argc, char** argv) { boost::timer t; t.restart(); for (int i=0; i<atoi(argv[1]); i++) foo (i); cout << "time : " << t.elapsed() << endl; t.restart(); for (int i=0; i<atoi(argv[1]); i++) foo2 (i); cout << "time : " << t.elapsed() << endl; } foo.cpp int foo (int x) { return x++; } Results of run: 1.8% performance hit to using linked foo instead of inline foo2. $ ./release/testlink.exe 100000000 time : 13.375 time : 13.14 And yes, the linker optimization flags (/LTCG) are on.
I'm not a compiler specialist, but I think the compiler has much more information available at disposal to optimize as it operates on a language tree, as opposed to the linker that has to content itself to operate on the object output, far less expressive than the code the compiler has seen. Hence less effort is spent by linker and compiler development team(s) into making linker optimizations that could match, in theory, the tricks the compiler does. BTW, I'm sorry I distracted your original question into the ltcg discussion. I now understand your question was a little bit different, more concerned with the link time vs. compile time static optimizations possible/available.
1,401,522
1,401,703
Scheduled Task Communication (using ITask interface)?
Is there anyway using the ITask interface to communicate with a scheduled task? I have tasks that users can cancel, pause, etc and a main console that displays information about the tasks. Right now I can only tell if they are running or not via the GetStatus method. What I would like to do is connect to the task and pass a string (potentially xml). Anyone know if this is possible?
The only strings you can pass to an ITask object are a directory path and command-line parameters. You cannot communicate with the task itself while it is running. On the other hand, if you use the Task Scheduler 2.0 interfaces instead, then ITaskDefinition has a Data property that you can assign arbitrary text to.
1,401,825
1,402,029
Callback from a C++ dll to a delphi application
Application is written in delphi 2010 and the underlying dll is a C++ dll. In ideal case, when your application is in C++; The dll makes a callback to an application when an event occurs. The callback is implemented through an interface. Application developers implements the abstract c++ class and pass the object to the dll. The dll will then make a callback to a member function of your implemented class. A classic callback pattern it is. But how do I pass a delphi object to the dll for it to make a callback.
I wouldn't really call that ideal. It is selfish and short-sighted to make a DLL that requires its consumers to use the same compiler as the DLL used. (Class layout is implementation-defined, and since both modules need to have the same notion of what a class is, they need to use the same compiler.) Now, that doesn't mean other consumers of the DLL can't fake it. It just won't be as easy for them as the DLL's designer intended. When you say the callback is implemented through an interface, do you mean a COM-style interface, where the C++ class has nothing but pure virtual methods, including AddRef, Release, and QueryInterface, and they all use the stdcall calling convention? If that's the case, then you can simply write a Delphi class that implements the same interface. There are many examples of that in the Delphi source code and other literature. If you mean you have a non-COM interface, where the C++ class has only pure virtual methods, but not the three COM functions, then you can write a Delphi class with the same layout. Duplicate the method order, and make sure all the methods are virtual. The Delphi VMT has the same layout as most C++ vtables on Windows implementations, at least as far as the function-pointer order is concerned. (The Delphi VMT has a lot of non-method data as well, but that doesn't interfere with the method addresses.) Just be sure you maintain clear ownership boundaries. The DLL must never attempt to destroy the object; it won't have a C++-callable destructor that the delete operator could invoke. If you mean that you have an arbitrary C++ class that could include data members, constructors, or non-pure methods, then your task is considerably more difficult. Follow up if this is the case; otherwise, I'd rather not address it right now. Overall, I'll echo Mason's advice that the DLL should use plain C-style callback functions. A good rule of thumb is that if you stick to techniques you see in the Windows API, you'll be OK. If you're not in control of how to interact with the DLL, then so be it. But if you can make the DLL's external interface more C-like, that would be best. And that doesn't mean you need to abandon the C++-style interface; you could provide two interfaces, where the C-style interface serves as a wrapper for your already-working C++style interface.
1,402,260
1,402,943
Static variable accessed from different compilation units potentially problematic?
When I started as at my first job as software developer I was assigned to create a system for that allows writing and reading C++ values (or objects) from and to a PDF document. This required a system for mapping types to an id and vice versa. The codebase was huge and there were several 'layers' of code (basic framework layer, tools-layer, view-layers, etc..). The proposed solution was to add a header file to each layer with an enum that contains ids for types defined in the particular layer. To avoid conflicts, each the first value of each enum would start with a offset value (1000, 2000, 3000, ...). As this system seemed a bit clumsy to me I decided to try something else, and came up with class for representing unique ids: // UniqueId.h class UniqueId { public: UniqueId(); operator int() const; private: int mId; static int sCounter; }; // UniqueId.cpp int UniqueId::sCounter = 0; UniqueId::UniqueId() { mId = ++sCounter; } UniqueId::operator int() const { return mId; } Instead of an enum, now simply a list of UniqueId objects could be created without fearing for conflicting ids. The person reviewing my code (software architect of the company) agreed with this at first. However, a day later he changed his mind and told me this system won't work. I vaguely remember him mentioning that there would be problems resulting from multiple compilation units. Today, some four years later, I still don't understand what the problem could have been. For as far as I know, the static variable will only be defined in one compilation unit (the one for UniqeId.cpp). So.. since StackOverflow is so abundant with veteran developers I'd like to take the opportunity to ask for some clarification. Would this indeed have been a problem? Or was my idea ok?
Is it important that the "types" be assigned the same IDs between different runs of your program? If not, everything should be fine. If so... How are different "types" grabbing their IDs? One way might be: class FooType { private: static UniqueId myId; ... }; This invokes the static initialization order fiasco that Fred Larson linked to. Since initialization order of statics is undefined, you might get different values assigned to myId from build to build, or if you're really unlucky, from run to run. You might instead create instances of UniqueId only when needed, say in the object's constructor or as a method with a static variable. For example: class BarType { private: const UniqueId &getMyId() { static UniqueId myId; return myId; } .... }; Now you might have to worry about thread safety (if you're developing a multithreaded program). Aside from that, UniqueId values depend greatly on the flow of your program, and will quite likely change from run to run. In one run of the program you may never need to instantiate BarType, and so it won't claim an ID. In another run you may need a BarType early on; in another you may need a BarType later. Even more sinister is that everything might work right for many builds, until you've forgotten all about this setup. Someone adds a new "type", juggles some of the existing types, or quite possibly makes a completely unrelated change. Then all of the sudden everything breaks for one of the reasons listed above.
1,402,341
1,402,396
Removing a node From Doubly Threaded LnkLst
Im trying to remove a single node from a doubly threaded linked list. What I have works..Its just terribly inefficient. I was wondering if I can get some expert advice or some while termination condition tips. Here is the function in which I remove 1 node from a set of Rating Nodes, stored in headByRating and a set of Name nodes, stored in headByName. All of which are sorted.... bool list::remove (const char * const name) { node *currByName = headByName; node *currByRating = headByRating; node *prev_node = NULL; while ( NULL != currByName && ( strcmp( name, currByName->item.getName() ) != 0 ) ) { prev_node = currByName; currByName = currByName->nextByName; prev_node->nextByName = currByName; } if ( currByName == headByName ) { currByName = currByName->nextByName; headByName = currByName; } else if ( currByName->nextByName == NULL ) {//then we must be at the end currByName = prev_node; currByName->nextByName = NULL; //return true; } else { currByName = prev_node; currByName->nextByName = currByName->nextByName->nextByName; //return true; } while ( NULL != currByRating && ( strcmp( name, currByRating->item.getName() ) != 0 ) ) { prev_node = currByRating; currByRating = currByRating->nextByRating; prev_node->nextByRating = currByRating; } if ( currByRating == headByRating ) // was it the head? { currByRating = currByRating->nextByRating; headByRating = currByRating; return true; } else if ( currByRating->nextByRating == NULL ) // could it be the tail? { currByRating = prev_node; currByRating->nextByRating = NULL; return true; } else { currByRating = prev_node; currByRating->nextByRating = currByRating->nextByRating->nextByRating; return true; } return false; } Yeah i just need help simplifing the code, making it more efficient. I hoping to combine and use only one while loop if thats possible.
Two choices: 1) Use a high level library that solves the problem. Boost MultiIndex containers allow shared nodes with multiple ordered/mapped organizations. 2) Instead of two (sorted by rating and name) singly linked lists, use two doubly linked lists. Then deletion of a given node is O(1). To find a node quickly by name, you could use an efficient map (hash table or balanced tree). If you don't mind scanning through one list to find the node, then that list doesn't need to be doubly linked. As for deletion for linked lists, you're right to suspect that your code can be simplified immensely. Either: 1) use a sentinel (dummy) node for the empty list; that way the "previous node" always exists for actual list items 2) instead of "pointer to previous node" in singly linked list deletion, store "pointer to "next pointer to this node"". Here's what I mean by 2): node **pn=&headByRating; // we will update headByRating=n via (*pn)=n if needed node *c=*pn; // we will have c == *pn except momentarily while ( c && strcmp(name, c->item.getName()) { pn=&c->nextByRating; // c is now the previous node c=*pn; // c is *pn again } // now (*pn) points to the node we want to delete, i.e. c *pn=c->next; // (*pn) skips right over c now. // delete c; // or else you leak memory; you didn't specify how nodes are allocated return true; This should be equivalent to your: while ( NULL != currByRating && ( strcmp( name, currByRating->item.getName() ) != 0 ) ) { prev_node = currByRating; currByRating = currByRating->nextByRating; prev_node->nextByRating = currByRating; } if ( currByRating == headByRating ) // was it the head? { currByRating = currByRating->nextByRating; headByRating = currByRating; return true; } else if ( currByRating->nextByRating == NULL ) // could it be the tail? { currByRating = prev_node; currByRating->nextByRating = NULL; return true; } else { currByRating = prev_node; currByRating->nextByRating = currByRating->nextByRating->nextByRating; return true; }
1,402,483
1,402,525
Why is it so slow iterating over a big std::list?
As title suggests, I had problems with a program of mine where I used a std::list as a stack and also to iterate over all elements of the list. The program was taking way too long when the lists became very big. Does anyone have a good explanation for this? Is it some stack/cache behavior? (Solved the problem by changing the lists to std::vector and std::deque (an amazing data structure by the way) and everything suddenly went so much faster) EDIT: I'm not a fool and I don't access elements in the middle of the lists. The only thing I did with the lists was to remove/add elements at the end/beginning and to iterate through all elements of the list. And I always used iterators to iterate over the list.
Lists have terrible (nonexistent) cache locality. Every node is a new memory allocation, and may be anywhere. So every time you follow a pointer from one node to the next, you jump to a new, unrelated, place in memory. And yes, that hurts performance quite a bit. A cache miss may be two orders of magnitudes slower than a cache hit. In a vector or deque, pretty much every access will be a cache hit. A vector is one single contiguous block of memory, so iterating over that is as fast as you're going to get. A deque is several smaller blocks of memory, so it introduces the occasional cache miss, but they'll still be rare, and iteration will still be very fast as you're getting mostly cache hits. A list will be almost all cache misses. And performance will suck. In practice, a linked list is hardly ever the right choice from a performance point of view. Edit: As a comment pointed out, another problem with lists is data dependencies. A modern CPU likes to overlap operations. But it can't do that if the next instruction depends on the result of this one. If you're iterating over a vector, that's no problem. You can compute the next address to read on the fly, without ever having to check in memory. If you're reading at address x now, then the next element will be located at address x + sizeof(T) where T is the element type. So there are no dependencies there, and the CPU can start loading the next element, or the one after it, immediately, while still processing an earlier element. That way, the data will be ready for us when we need it, and this further helps mask the cost of accessing data in RAM. In a list, we need to follow a pointer from node i to node i+1, and until i+1 has been loaded, we don't even know where to look for i+2. We have a data dependency, so the CPU is forced to read nodes one at a time, and it can't start reading future nodes ahead of time, because it doesn't yet know where they are. If a list hadn't been all cache misses, this wouldn't have been a big problem, but since we're getting a lot of cache misses, these delays are costly.