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,454,268 | 1,459,974 | What is the reason for a segmentation fault with this C++ code using lists? | I have some complicated C++ code but the problem narrows down to doing a push_back on a list of structures:
list<cache_page> cachedPages;
void f()
{
cache_page cpage(a,b);
cachedPages.push_back(cpage);
}
I have commented all the data members of the struct cache_page and still the error persists. If I comment ... | You're crossing the streams. Haven't you seen Ghostbusters? Don't cross the streams.
You're crossing the streams here:
class B : public A < B *>
I don't understand the point of this. What are you trying to do? CRTP? This is not the way it's done.
The problem is not in the push back, the problem is, "this" being invali... |
1,454,344 | 1,454,373 | C++ - cloning base class | I have something like that:
Class Foo : Base {.."my stuph" ..};
int main() {
Base *b = new Base;
Foo f (b); <== **error** "invalid conversion from Base to Foo."
..
}
How can I clone b to f?
In "my stuph" I have functions which make workout between Foo and Base.
I can't change Base to much while it's writte... | You can't automatically make a derived class out of base one. You can do vice versa and create a base class out of the derived, however, and this might confuse you.
To do what you want, you should add proper constructor to Foo and think how you will actually create information missing in a Base instance to constitute ... |
1,454,455 | 1,454,688 | Event-Driven Client/Server Design with C++ | I am designing a game server with scripting capabilities. The general design goes like this:
Client connects to Server,
Server initializes Client,
Server sends Client to EventManager (separate thread, uses libevent),
EventManager receives receive Event from Client socket,
Client manages what it received via callbacks.
... | You can use a reference counted pointer like boost::shared_ptr<> to simplify memory management. If the manager's client list uses shared_ptrs and the code that calls the callbacks creates a local copy of the shared_ptr the callback is called on, the object will stay alive until it is removed from the manager and the ca... |
1,454,843 | 1,454,864 | variable length array of classes | I have some code which is effectively this:
class dummie_type
{
public:
int a;
void do_stuff()
{
// blah
}
};
class dummie_type dummie[10];
void main()
{
subroutine();
}
void subroutine()
{
dummie[3].a = 27; // etc...
dummie[5].do_stuff();
}
Note that the array of classes is... |
I know that this will involve making a global pointer, and then setting that to point to a block of memory that gets malloc'ed or new'ed in main and I know that I will have to change the "." characters to "->" but other than that I keep failing to produce something that my compiler will accept. I'm particularly uncert... |
1,454,949 | 1,455,020 | How do I test features that are not in the public interface? | I'm designing a library for myself that allows the chaining of streams of data. Let me paint the scenario:
I create a SerialDatastream which is the bottom layer and reads from and writes to a COM port.
I pass a pointer to this to the constructor of a ProtocolDatastream, which interprets the bytes when read from the se... | What you need are unit tests for Tee itself; independent of its use later in other unit tests as part of the plumbing.
For these new unit tests, the "invisible part" is actually what they must cover. This is no longer a hidden feature but part of the API of Tee.
Later, when you're sure that Tee works correctly (and hav... |
1,455,190 | 1,456,878 | How to access MySQL from multiple threads concurrently | We're doing a small benchmark of MySQL where we want to see how it performs for our data.
Part of that test is to see how it works when multiple concurrent threads hammers the server with various queries.
The MySQL documentation (5.0) isn't really clear about multi threaded clients. I should point out that I do link ag... | As maintainer of a fairly large C application that makes MySQL calls from multiple threads, I can say I've had no problems with simply making a new connection in each thread. Some caveats that I've come across:
Edit: it seems this bullet only applies to versions < 5.5; see this page for your appropriate version: Like... |
1,455,320 | 1,549,100 | How to get the cpu usage per thread on Mac OSX | I am looking for an OS level API to account for cycles consumed by a specific thread in OSX.
This is similar to this question (and answer) but in OSX.
| You should be able to get this info from the thread_basic_info structure, returned by a call to thread_info.
|
1,455,333 | 1,455,384 | how to use binder and bind2nd functors? | How to use binder2nd, bind2nd, and bind1st?
More specifically when to use them and are they necessary?
Also, I'm looking for some examples.
| They're never, strictly speaking, necessary, as you could always define your own custom functor object; but they're very convenient exactly in order to avoid having to define custom functors in simple cases. For example, say you want to count the items in a std::vector<int> that are > 10. You COULD of course code...:
... |
1,455,401 | 1,455,420 | Redefine a derived class' variable | Is the following valid? Or how can I get something close to this.
template<class T_> class Template {
//something
};
class Parent {
public:
Template<Parent> variable;
Parent() : variable(this) { }
};
class Derived : public Parent {
public:
Template<Derived> variable;
Derived() : Parent() { }
}
Thank... | It's technically "valid" in that your compiler has to accept it (it may warn you, and IMHO it should), but it doesn't do what you think it does: Derived's variable is separate from Parent's, and is not getting explicitly initialized (so it uses the default ctor for Template<>).
|
1,455,600 | 1,460,184 | MySQL Connector C++ - make Error 1 | I'm writing an application in C++ (using Eclipse with Linux GCC) that's supposed to interact with my MySQL server.
I've downloaded the MySQL Connector C++ a, precompiled, and copied the files into the directories (/usr/lib, /usr/include). I've referenced in in the GCC C++ Linker Section of the Project Properties in Ec... | The Solution is quite simple - compile your own Connector. I did it with the 1.0.5 version of the Connector. to do it, you need to install the package via
sudo apt-get install mysql-client
In the directory of the source package you downloaded (and extracted), type
cmake .
apparently, in three files of the driver, refer... |
1,456,225 | 1,456,261 | Spinlocks, How Useful Are They? | How often do you find yourself actually using spinlocks in your code? How common is it to come across a situation where using a busy loop actually outperforms the usage of locks?
Personally, when I write some sort of code that requires thread safety, I tend to benchmark it with different synchronization primitives, and... | It depends on what you're doing. In general application code, you'll want to avoid spinlocks.
In low-level stuff where you'll only hold the lock for a couple of instructions, and latency is important, a spinlock mat be a better solution than a lock. But those cases are rare, especially in the kind of applications where... |
1,456,342 | 1,456,586 | Are there any free tools to help with automatic code generation? | A few semesters back I had a class where we wrote a very rudimentary scheme parser and eventually an interpreter. After the class, I converted my parser into a C++ parser that did a reasonably good job of parsing C++ as long as I didn't do anything fancy with the preprocessor or macros. I could use it to read over my c... | A complete parser-building tool like ANTLR or YACC is necessary if you want to parse C++ from scratch, but it's overkill for your purposes.
It reads over my source files, makes a list of classes, their members, their functions, etc. which is then used to generate new code.
Two main options:
GCC-XML can generate a list... |
1,456,706 | 1,456,972 | Error linking with 3rd party static library built with previous version of Visual Studio | I am working on a project that links to a 3rd party static library (herin refered to as EXTERNALLIB). In Visual Studio 2005 I was able to link to EXTERNALLIB and create a usable executable. Now we are using Visual Studio 2008 and I am receiving the following error:
fatal error C1047: The object or library file EXTERN... | You problem is likely to result from "the code is written in C++". The ABI for C++ linkage is essentially completely unspecified by any standard, and is notoriously changeable from compiler to compiler. I suspect that VS is trying to tell you that the ABI has changed again, and that as a result it cannot link directly ... |
1,456,840 | 1,456,850 | Why is it called 'wchar_t' and not simply 'wchar'? | I've often wondered why C++ went with the name wchar_t instead of simply wchar, and I've never been able to find an answer. Search engines are no help because they think I'm asking about Windows' WCHAR type. Any ideas?
| That's a legacy from C, where wchar_t is a typedef, and typedefs have that suffix in the C Standard Library.
|
1,457,184 | 1,462,498 | MouseProc hook and WM_LBUTTONDBLCLK | I have a hook setup for getting mouse events in a plugin I develop. I need to get the WM_LBUTTONDBLCLK, and I expect the message flow to be:
WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK
If I call the next hook when dealing with the first WM_LBUTTONDOWN, then the flow is as expected. However, if I return my own result... | After having done a little reading over at the MSDN, I think the explanation of this behaviour lies in this remark on the WM_LBUTTONDBLCLK page:
Only windows that have the CS_DBLCLKS
style can receive WM_LBUTTONDBLCLK
messages, which the system generates
whenever the user presses, releases,
and again presses t... |
1,457,319 | 1,457,483 | Trying to choose SQL API library | I am just beginning to learn how to write software that accesses an SQL server. It seems that each server implementation (Postgres, MySQL, etc.) offers API libraries for various languages (my code is in C and C++, though solutions for Java and Python would also interest me). I'm a little wary of depending on these li... | Indeed, ODBC/JDBC are libraries that help make the calling interface standard between vendors, but you're right that each respective RDBMS has its own flavor of SQL. ODBC/JDBC doesn't help abstract the SQL syntax.
One solution to move literal SQL out of your application code is to implement queries in stored procedure... |
1,457,431 | 1,457,545 | C/C++: Size of builtin types for various compilers/platforms | Where can I go to get information about the size of, say, unsigned int compiling under gcc for Mac OS X (both 32 and 64 bits)? In general I'd love to have a resource I can go to with a compiler/settings/platform/type and be able to look up how big that type will be. Does anyone know of such a thing?
Update: Thanks for ... | If you can't write a program to find out, you should consult the ABI (Application Binary Interface) specification for the compiler/platform. It should document the sizes, alignments, endianness, etc. of the basic primitive types supported.
|
1,457,669 | 1,457,675 | C++ Dynamic Array Access Violation | **** Sorry for the confusion regarding numCars in the original post. I modified the code to be consistent with the original ******
The following academic program is a simplified version of the original problem but it focuses on the issue that I have yet to resolve. There are 2 classes and a main method to this problem ... | void addCar(const Car& car)
{
cars[numCars++] = car; // Access Violation
}
You never initialize numCars - it contains some value from the heap which is almost definitely non-zero. This causes you to read beyond the end of the cars array and into inaccessible memory. You should set numCars to 0 in your construct... |
1,457,842 | 1,457,873 | Is this good code? (copy constructor and assignment operator ) | For one reason or another, I'm forced to provide both a copy constructor and an operator= for my class. I thought I didn't need operator= if I defined a copy ctor, but QList wants one. Putting that aside, I hate code duplication, so is there anything wrong with doing it this way?
Fixture::Fixture(const Fixture& f) {
... | This is bad, because the operator= can't rely on a set-up object anymore. You should do it the other way around, and can use the copy-swap idiom.
In the case where you just have to copy over all elements, you can use the implicitly generated assignment operator.
In other cases, you will have to do something in additi... |
1,458,180 | 1,458,182 | vtable for .. referenced from compile error xcode | I was getting the following error compiling an iPhone project:
"vtable for oned::MultiFormatUPCEANReader", referenced from:
__ZTVN4oned23MultiFormatUPCEANReaderE$non_lazy_ptr in MultiFormatUPCEANReader.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
Anybody know how I may fix it?
| The problem seemed to be that in the class MultiFormatUPCEANReader I had declared a constructor and destructor, but had not written a body for the destructor, this was causing this annoying problem. Hope this helps somebody solve their compile error. This is a terrible compiler error with little information!
|
1,459,001 | 1,459,062 | In C++, passing a pointer still copies the object? | I've been reading for an hour now and still don't get what is going on with my application.
Since I am using instances of object with new and delete, I need to manage the memory myself. My application needs to have long uptimes and therefore properly managing the memory consumption is very crucial for me.
Here's the st... | The variable bytes is the pointer to the data, i.e. the memory location of the data.
But that is not what you are printing, you are printing out the address where this pointer is located, i.e. the address on the stack where the pointer is passed. So
printf(" |---DUMPING DATAPACKET refId: %d ....\n", &bytes);
sh... |
1,459,045 | 1,461,225 | Combining Bitmaps / ImageLists (Win32) | Is it possible to create an image list from multiple bitmaps, or to combine multiple image lists into one.
For sake of simplicity, same element dimensions and transparent color could be assumed.
Reason: I am currently dealing with a very long image list containing four groups of icons and notable "reserved" areas betw... | ImageList_Add can add a bitmap with several images to an existing image list. Is that what you're looking for?
|
1,459,257 | 1,459,423 | C++ and Smart Pointers - how would smart pointers help in this situation? | Much to my shame, I haven't had the chance to use smart pointers in actual development (the supervisior deems it too 'complex' and a waste of time). However, I planned to use them for my own stuff...
I have situations regarding de-initing a module after they are done, or when new data is loaded in. As I am using pointe... | Make each of your classes implement a destructor which performs all the cleanup/deinitialization you need for that class.
Create an instance of the class, and wrap it in a boost::shared_ptr.
Then pass copies of that to every function which needs access to the instance.
And the smart pointer will ensure that once the ob... |
1,459,344 | 1,459,376 | Qt and serial port programming | Is there any serial port facilities in Qt ?
If not, which crossplatform (desirable) libraries (for working with serial port and, maybe, with other I/O ports), do you recommend ?
| Take a look at the Project QextSerialPort.
|
1,459,443 | 1,459,450 | output a list of functions called by a source file | Is there a flag I can set so that the compiler (linker?) will output a list of all the functions called by (not just defined in) each separate source file during the compilation(linking) process?
Thanks,
| I don't know if VS can do that, but you can use doxygen to generate a call graph for each function.
|
1,459,808 | 1,460,042 | Global (process wide) properties in Win32 | I am trying to share some data across DLLs in a project which has an extremely complicated dependency structure (numberous DLLs).
I want to be able to associate a key with some data in one part of the application, and then extract that data by supplying the appropriate key in some other part of the app. In a way, one ... | To be clear here there is one exe with multiple DLL's in only one process but multiple modules. So you aren't looking for inter-process communications.
In answer I see two strategies:
use Windows API atoms which are slightly limited (basically only string data) which can work within or between processes.
If you write ... |
1,459,865 | 1,463,215 | IWebBrowser2 issues - how to open documents in new windows? | I have IWebBrowser2 ctrl embedded into my own dialog. I want to simply
display a promo banner within it from my url. How to disable all popup
menu items from the control and force it to open links in new window
(currently when I click on link in the banner, it is being opened
within the same control).
Regards
Dom... | Have a look at the following article:
WebBrowser Customization
|
1,460,007 | 1,460,097 | WAV file from captured PCM sample data | I have several Gb of sample data captured 'in-the-field' at 48ksps using an NI Data Acquisition module. I would like to create a WAV file from this data.
I have done this previously using MATLAB to load the data, normalise it to the 16bit PCM range, and then write it out as a WAV file. However MATLAB baulks at the fil... | I think you can use libsox for this.
|
1,460,010 | 1,479,465 | Best C++ RTP/RTSP library | I'm looking for a RTP/RTSP library in C++. I found pjsip but it is more C-style. I'm looking for more OO library.
| JRTPLIB is very nice, and used in well-known projects such as SightSpeed (and lots of little ones). Pretty well-designed, very flexible license; pretty easy to get things right with it.
|
1,460,185 | 1,470,028 | Use Pantheios logging framework from a dll | Im a trying to use pantheios logging framework from inside a c++ dll. I have successfully built the dll and it executes through my test application (C++ MFC Application).
I have used implicit linking with the following includes:
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#... | Some further tests showed that the logging from the dll works if I link it to a console application instead of a windows application. And if I change the backend to "file" instead of "console" the windows application do log correctly to the file. So the problem seem to be that the windows application doesn't have a "co... |
1,460,361 | 1,460,372 | How to set application icon in a Qt-based project? | How do you set application icon for application made using Qt? Is there some easy way? It's a qmake-based project.
| For Qt 5, this process is automated by qmake. Just add the following to the project file:
win32:RC_ICONS += your_icon.ico
The automated resource file generation also uses the values of the following qmake variables: VERSION, QMAKE_TARGET_COMPANY, QMAKE_TARGET_DESCRIPTION, QMAKE_TARGET_COPYRIGHT, QMAKE_TARGET_PRODUCT, ... |
1,460,377 | 1,460,416 | How to detect an overflow in C++? | I just wonder if there is some convenient way to detect if overflow happens to any variable of any default data type used in a C++ program during runtime? By convenient, I mean no need to write code to follow each variable if it is in the range of its data type every time its value changes. Or if it is impossible to ac... | Consider using boosts numeric conversion which gives you negative_overflow and positive_overflow exceptions (examples).
|
1,460,703 | 2,797,990 | Comparison of arrays in google test? | I am looking to compare two arrays in google test. In UnitTest++ this is done through CHECK_ARRAY_EQUAL. How do you do it in google test?
| I would really suggest looking at Google C++ Mocking Framework. Even if you don't want to mock anything, it allows you to write rather complicated assertions with ease.
For example
//checks that vector v is {5, 10, 15}
ASSERT_THAT(v, ElementsAre(5, 10, 15));
//checks that map m only have elements 1 => 10, 2 => 20
ASSE... |
1,460,719 | 1,460,815 | determine value range of template type in C++ | In a template function, I like to determine the range for the value of its template type. For specific type, like int, INT_MAX and INT_MIN are what I want. But how to do the same for a template type?
Thanks and regards!
| For numeric types, you can use the std::numeric_limits class template in the <limits> header.
|
1,460,863 | 1,463,072 | Windows Mobile Sockets SSL Communication library | I have a Win32 application that uses boost::asio and openssl library but it seems that they are not supported under WM, am I correct?
Can anyone suggest WM API/library for WM Sockets, I need to connect to a server through SSL connection.
Is the only option for me WinSocks + OpenSSL?
| While I don't know of any other libraries for WM that provide socket and ssl connectivity, I can confirm that sockets and OpenSSL do work fine on WM5 and above devices. You have to jump through a few hoops to get openssl built for wm5 and ARM, as there are some parts of the c runtime missing, these are plugged with thi... |
1,460,936 | 1,461,008 | Why STL implementation is so unreadable? How C++ could have been improved here? | For instance why does most members in STL implementation have _M_ or _ or __ prefix?
Why there is so much boilerplate code ?
What features C++ is lacking that would allow make vector (for instance) implementation clear and more concise?
| Implementations use names starting with an underscore followed by an uppercase letter or two underscores to avoid conflicts with user-defined macros. Such names are reserved in C++.
For example, one could define a macro called Type and then #include <vector>. If vector implementations used Type as a template parameter ... |
1,460,949 | 1,461,046 | C++ logical operators return value | Here is some code I'm writing in C++. There's a call to an addAVP() function
dMessage.addAVP(AVP_DESTINATION_HOST, peer->getDestinationHost() || peer->getHost());
which has two versions: one overloaded in the second parameter to addAVP(int, char*) and another to addAVP(int, int). I find the C++ compiler I use calls th... | It is legal in C++ to overload the logic operators, but only if one or both of the arguments are of a class type, and anyway it's a very bad idea. Overloaded logic operators do not short circuit, so this may cause apparently valid code elsewhere in your program to crash.
return p && p->q; // this can't possibly deref... |
1,461,064 | 1,461,071 | Are member variables of an object that is on the heap also automatically on the heap? | class A
{
public:
A();
~A();
int X;
};
A::A()
{
X = 5;
int Y = 4;
}
//..... in another file
A * objectOnHeap = new A();
In this case, since "objectOnHeap" is on the heap, is X also on the heap even though it wasn't specifically new'd up? And in this case Y is allocated on the stack (and of course goes out... | Yes. It's on the heap. Basically, the space allocated to an object on the heap is big enough to hold all its member variables.
|
1,461,145 | 1,461,213 | Where can I find source of unhook function used in STL implementation provided with g++ | It is used in /usr/include/c++/4.3/stl_list.h on my system (current Ubuntu).
| http://gcc.gnu.org/
Have a look at the Download or "Live" Sources sections.
|
1,461,276 | 1,461,294 | std::vector reserve() and push_back() is faster than resize() and array index, why? | I was doing a quick performance test on a block of code
void ConvertToFloat( const std::vector< short >& audioBlock,
std::vector< float >& out )
{
const float rcpShortMax = 1.0f / (float)SHRT_MAX;
out.resize( audioBlock.size() );
for( size_t i = 0; i < audioBlock.size(); i++ )
{
... |
Does resize initialize the newly allocated vector where reserve just allocates but does not construct?
Yes.
|
1,461,331 | 1,469,750 | Writing my own shell... stuck on pipes? | For the past few days I have been attempting to write my own shell implementation but I seem to have gotten stuck on getting pipes to work properly. I am able to parse a line and fork off the commands between the pipes (ex: ls | sort) individually but can't seem to get them to pipe input from one into the other.
I thi... | First suggestion: Symbolic constants are better than magic numbers.
const int PIPE_READ = 0;
const int PIPE_WRITE = 1;
int fd[2];
pipe(fd);
// Now you can refer to fd[PIPE_READ] and fd[PIPE_WRITE].
Second suggestion: Take a step back and think about what you're trying to accomplish.
You want to spawn two processes, ... |
1,461,340 | 1,461,358 | error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Rectangle' (or there is no acceptable conversion) | I'm required to write a function to overload the ==operator to compare width, height and colour. I need to return 'Y' if its equal and 'N' if its not.
This is my code which I think is correct, but keeps giving me the error:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Rectang... | "<<" is higher precedence than "==". Put your comparison in parentheses:
cout << "Are B and C equal? Ans: " << (rectB == rectC) << endl;
|
1,461,432 | 1,461,449 | What is array to pointer decay? | What is array to pointer decay? Is there any relation to array pointers?
| It's said that arrays "decay" into pointers. A C++ array declared as int numbers [5] cannot be re-pointed, i.e. you can't say numbers = 0x5a5aff23. More importantly the term decay signifies loss of type and dimension; numbers decay into int* by losing the dimension information (count 5) and the type is not int [5] any... |
1,461,805 | 1,461,843 | How can I compare similar codebases? | We have several C++ projects that were built from the same codebase. There's a lot of similarities and common code between them but they were developed independently; source was not shared in any way. Classes and files will have been renamed even if the underlying code hasn't changed and individual lines will have been... | I don't have much experience with this sort of thing, but it made me think back to my school days when our University would run everyones code through a program to find cheaters. This brought me to the following link:
Source Code Similarity Detection
It names some open source and commercial software that should meet ... |
1,461,832 | 1,461,938 | overloading operator<< for use with ostream | I am using CPPUnit to test a class in my program. This class (SCriterionVal) is somewhat unique because it has conversion operators for a lot of types (it's essentially a dynamic type value class). When I compile test cases that test it using CPPUNIT_ASSERT_EQUAL(), I get compilation errors about "operator<< is ambig... | Try defining operator<< as a friend inline function inside the class definition. I always find this way works the best, especially for templates.
For example, Boost.Random defines operator<< inside exponential distribution's declaration:
template<class CharT, class Traits>
friend std::basic_ostream<CharT,Traits>&
... |
1,461,867 | 1,461,962 | why does this work? (finding odd number in c++) | for (unsigned int i = 1; i <= 100; i++) {
if (i & 0x00000001) {
std::cout << i<<",";
}
}
why does (and how): if( i & 0x00000001 ) figure out the odd number?
| 0x00000001 is 1 in binary, although it's written in hexadecimal (base-16) notation. That's the 0x part.
& is the bit-wise 'AND' operator, which is used to do binary digit (bit) manipulations.
i & 1 converts all of the binary digits of i to zero, except for the last one.
It's straightforward to convert the resulting 1-b... |
1,462,078 | 1,474,071 | Why won't Direct3D recover after unplugging a monitor in Windows XP? | An interesting bug came up that I'm having no luck with. In a windowed Direct3D9 program using native code, I handle a device lost using something similar to the following:
void MyClass::RecoverFromDeviceLost(LPDIRECT3DDEVICE9 deviceToRecover, D3DPRESENT_PARAMETERS devicePresentParams )
{
HRESULT hr = deviceToRe... | I ended up testing a different program that uses DirectX for graphics, just to see if the problem was just with the one program. The other application recovered with no problems from a monitor unplug or KVM switchover in Windows XP. The main difference between the two programs was that the working one used DXUT to ma... |
1,462,341 | 1,462,350 | "GetOrCreate" - does that idiom have an established name? | Ok, consider this common idiom that most of us have used many times (I assume):
class FooBarDictionary
{
private Dictionary<String, FooBar> fooBars;
...
FooBar GetOrCreate(String key)
{
FooBar fooBar;
if (!fooBars.TryGetValue(key, out fooBar))
{
fooBar = new FooBar... | Lazy Loading
http://en.wikipedia.org/wiki/Lazy_loading
|
1,462,359 | 1,472,117 | How can I share data between C++ and Lua? | I have been looking for tutorials demonstrating how to share a C++ object with Lua using the API. Most tutorials just show how to export a class.
I would like to start very simple and expose a variable (say int myVar = 5) in such a way that a change in Lua will be reflected in the C++ application.
Does anyone know any ... | As sbk mentioned, you'd access your variable as a member of a userdata:
print(cside.myVar) -- 5
Here is some sample code to do this using the Lua API. Its straightforward, although tedious. You'll either want to make your own code generator or using something like swig or tolua++
/* gcc -o simple simple.c -llua -lm ... |
1,462,599 | 1,464,515 | Is there any memory browser in QtCreator? | I can't find it. In the watcher window I can manually type memory addresses but I'd like to see bigger chunks of memory...
If this doesn't exist, is there any other free memory mapper for the Mac (except for XCode and Eclipse)?
Thanks,
rui
| The only way to do this that I've found is to type gdb commands in to the debugger - you can get GDB to dump areas of memory... hopefully there'll be this feature in a newer release!
|
1,462,829 | 1,462,884 | What is the most elegant and efficient way to model a game object hierarchy? (design bothers) | I've got the following code, think simple shooter in c++:
// world.hpp
//----------
class Enemy;
class Bullet;
class Player;
struct World
{
// has-a collision map
// has-a list of Enemies
// has-a list of Bullets
// has-a pointer to a player
};
// object.hpp
//-----------
#include "world.hpp"
struct Object
{... | This is probably the biggest issue I encounter when designing similar programs. The approach I've settled on is to realize that an object really does not care about where it is in absolute terms. All it cares about is what is around it. As a result, the World object (and I prefer the object approach to a singleton for ... |
1,462,932 | 1,462,943 | Is there a 'restart' function in Windows/C++ | In a windows project I am working on, I intend to have a menu selection that copletely restarts the app. Is there a Windows or C++ function that does this?
| There isn't a built-in for this, but a well-designed application can simply stop everything that's going on and then loop back to the start. If you want a true 'fresh start', you will have to spawn a new process (possibly as the last thing you do before the old one shuts down.)
|
1,463,040 | 1,463,050 | Does Windows have its own 'call other .exe' function (C++) | I know in C++ there is a function
system("example.exe");
that runs another program, put it requires the include stdlib.h.
Because I am already including 'windows.h', is there an equivilant to the system() function in Windows?
| There is CreateProcess to run a specific executable, or ShellExecute to run programs or open documents with their associated program.
If portability to other platforms is any issue at all, I'd stick with system. #including stdlib.h won't kill you ;)
|
1,463,148 | 1,474,613 | Is it possible to prevent an RAII-style class from being instantiated "anonymously"? | Suppose I have an RAII-style C++ class:
class StateSaver
{
public:
StateSaver(int i) { saveState(); }
~StateSaver() { restoreState(); }
};
...to be used like so in my code:
void Manipulate()
{
StateSaver save(1);
// ...do stuff that modifies state
}
...the goal being to enter some state, do stuff, then... | I actually had to tweak my solution in a bunch of ways from the variant Waldo posted, but what I eventually got to is a macro-ized version of:
class GuardNotifier
{
bool* notified;
public:
GuardNotifier() : notified(NULL) { }
void init(bool* ptr) { notified = ptr; }
~GuardNotifier() { *notified = true... |
1,463,150 | 1,463,194 | C++: Pointer to class member function inside a non-related structure | I've done a bit of reading online as to how to go about this and I think I'm doing it correctly... My goal is to have an array of structure objects that contain pointers to member-functions of a class.
Here's what I have so far...
typedef void (foo::*HandlerPtr)(...);
class foo
{
public:
void someFunc(...);
// ... | someFunc() is not a static method, so you need a foo object instance in order to call someFunc() via your pointer-to-method variable, ie:
foo f;
f.*(stuff[0].handler)();
Or:
foo f;
HandlerPtr mthd = stuff[0].handler;
f.*mthd();
Or, using pointers:
foo *f = new foo;
f->*(stuff[0].handler)();
delete f;
Or:
foo *f = ne... |
1,463,409 | 1,463,435 | How to check for NULL in c++? | Let say for example, I have a struct, and an array of the struct. What I want to do is to iterate through the array and check if any of the item is a null. I tried checking the item against NULL and (struct *) 0, that don't seem to work. Is there any reliable way to check for null value?
UPDATE Sample Code
struct Test{... | If you have an array of structs, then there are no pointers, so it doesn't make sense to check for null.
An array of n structs is literally n of those structs laid out one after the other in memory.
Could you change it to an array of pointers to structs, initialise them all to NULL, and create them as you need them? I... |
1,463,515 | 1,463,570 | How can I use Dynamic Methods in C++ | I've found myself writing some repetitious code in C++. I'm using some auto-generated, such that if I want to deal with Foo, Bar, & Baz they all have fairly similar method. E.g., get_foo, get_bar, get_baz, etc.
For each "thing" I more or less have to do the same types of thing. Check if it exists, if it does, get th... | Sure (code untested, I might have missed some problem with member pointers and type deduction, or I might just have left bugs):
template <typename T, typename M, typename F, typename G>
void doChecks(T *obj, M has_member, F get_fn, G getlog_fn) {
if (obj->*has_member) {
if (obj->*get_fn().has_log()) {
... |
1,464,098 | 1,464,106 | How can I get c-function based diffs? | Our team uses svn to manage our source. When performing a re-factor on a C file, I occasionally both change functions and move them within the file. Generally I try to avoid moving functions, because it makes the default svn diff get a bit addled about what's going on, and it often provides a diff which is more confusi... | One way to do it with the tools you have is to move the functions first, check them in, then change them. Or have two enlistments, and when you see this happening move them in one, svn up the other, resolve the merge issue. It moves the work to you, but makes code reviews easier.
|
1,464,439 | 1,464,660 | Using std::bind2nd with references | I have a simple class like this:
class A
{
public:
void f(const int& n)
{
std::cout<<"A::f()" << n <<"\n";
}
};
and I am trying to use it like this:
std::vector<A> vec;
A a;
vec.push_back(a);
std::for_each(vec.begin(), vec.end(), std::bind2nd(std::mem_fun_ref(&A::f), 9));
But when I compile the co... | You can't do that easily, sorry. Just consider it one of those cases not covered by std::bind1st and std::bind2nd (kinda like 3-argument functions etc). Boost would help - boost::bind supports references transparently, and there's also boost::ref.
If your implementation supports TR1 - latest g++ versions and VC++2008 S... |
1,464,510 | 1,464,930 | Storage Card Problem In windows mobile | I m making windows mobile application, it refers some DLL's but i have some problem here.
Imagine my application is installed in storage card related DLL's present in Storage card only,
if i launch application it refers some of DLL, now i will remove the storage card, still my application will be running,it will not qu... | You can use the function SHChangeNotifyRegister to WM_FILECHANGEINFO message.
After you subscribe, you will be receiving events with ids such as SHCNE_DRIVEREMOVED or SHCNE_MEDIAREMOVED, so you can trigger some actions when storage card is removed.
To use native functions from the compact framework, use P/Invoke.
|
1,464,591 | 1,464,601 | How to create a bold, red text label in Qt? | I want to write a single, bold red line in my application using Qt.
As far as I understand, I would create a QLabel, set its textFormat to rich text and give it a rich text string to display:
QLabel *warning = new QLabel;
warning->setTextFormat(Qt::RichText);
warning->setText("{\\rtf1\\ansi\\ansicpg1252 {\\fonttbl\\f0\... | Try using HTML formatting: <b><font... etc </b>.
Qt Designer does it like this: <span style=" font-size:8pt; font-weight:600; color:#aa0000;">TextLabel</span>
|
1,464,711 | 1,464,759 | How to detect if errno_t is defined? | I'm compiling code using gcc that comes from Visual C++ 2008. The code is using errno_t, but in some versions of gcc headers including <errno.h> doesn't define the type. How do I detect if the type is defined? Is there a define that signals that the type was defined? In the case it isn't defined I'd like to provide the... | You can't check for a typedef the way you can for a macro, so this is a bit on the tricky side. If you're using autoconf, this patch shows the minimum changes that you need to have autoconf check for the presence of errno_t and define it if it's missing (the typedef would be placed in a file that includes your generate... |
1,464,751 | 1,465,552 | I want to use Infocardapi.dll in Delphi/WIN32 but would like a header file for it | Microsoft has this nice little feature called CardSpace. This is a Microsoft implementation of InfoCards. Microsoft has a nice document which explains how it can be used, which is useful. And doing a Google search doesn't provide me many useful answers but it does provide an enormous amount of noise. (Mostly because pe... | There is an InfoCard.h file included with Microsoft's Windows SDK which should be what you need. Bit of a hefty download for a single file if you don't already have it - you might be better visiting the MSDN reference for the CardSpace API and getting the info from there.
|
1,464,758 | 1,464,808 | [c++ / pointers]: having objects A and B (B has vector member, which stores pointer to A), knowing A is it possible to retrieve pointer to B? | While trying to learn c++, I tried to implement class representing very basic trie. I came up with the following:
class Trie {
public:
char data;
vector<Trie* > children;
Trie(char data);
Trie* addChild(Trie* ch); // adds child node
(skipped others members/methods)
};
Method addChild checks i... | You need to add something like
Trie* parent;
or
Trie* previoussibling;
Trie* nextsibling;
to the class to get directly from firstchild to secondchild or vice-versa, or to go up from one of the children to t.
Note that if you need this kind of relationship then you will require more maintenance when adding and removin... |
1,464,932 | 1,464,976 | How to make the ToolTip appear in the foreground of the floating CPaneDialog? | Does anybody has a hint for the following problem?
I have a derived class from CPaneDialog, it contains just one button. I want to show a tooltip if the mouse is over it. For this I use CMFCToolTipCtrl:
// Create the ToolTip control.
m_ToolTip.Create(this, TTS_ALWAYSTIP | TTS_NOPREFIX);
m_ToolTip.Activate(TRUE);
CMFCT... | set the topmost property.
m_ToolTip.SetWindowPos(&CWnd::wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
|
1,465,018 | 1,465,034 | Switch Programming Language | I've forgotten how to switch programming languages in Visual Studio 2008. I need to switch from C++ to C#. Help!
| Do you mean you want to switch the key-mappings ?
Main menu > Tools > Options > Environment > Keyboard
Use the dropdown that says Apply keyboard mapping scheme.. to switch from C++ to C#
|
1,465,112 | 1,531,429 | SetWindowsHook stops working after some time | I defined a global hook on WM_MOUSE that works perfectly for some time. It post a message to a specific window each time the mouse move.
After some random time the hook stop sending messages. If I unregister and register the hook it works again. I suppose some specific thing happening in Windows cause the hook to stop,... | Did you check, if the hook is still installed when its not called any more (i.e. check the return value from BOOL UnhookWindowsHook)?
Possibly another hook is installed that does not preserve your hook, not calling CallNextHookEx().
|
1,465,494 | 1,465,957 | service and registry | I have a problem in understanding the relationship between services and registry.
I have the task of taking my windows C++ program and transform it from simple application to a service.
I read that I need to produce some more functions as: start stop resume install.
The problem is:
Why I need the regisrty ?
how I ente... | I'm not aware of any documented relationship between services and the registry. Services can use the registry to store their settings, just like any other application, but they're not required to.
Formally, you don't need the registry. You simply need to install the service using the relevant API functions. As part of... |
1,465,549 | 1,465,609 | CMFCButton with Vista Style | I can't seem to get a CMFCButton to be displayed in Vista style in a dialog box application. I'm using VS2008 with MFC Feature Pack.
Here are some steps to reproduce my problem:
Create a new MFC Project;
Specify a Dialog based project.
Add two buttons to the main dialog.
Add a variable for each button. Make one of the... | The CMFCButton has the BS_OWNERDRAW style set by default - you can remove it in the OnInitDialog() for your dialog:
mfcButton.ModifyStyle(BS_OWNERDRAW, 0, 0);
However, removing the owner draw style results in many of the methods of CMFCButton being rendered useless (e.g. SetTextColor). You can get the button to render... |
1,465,655 | 1,465,760 | Unmanaged C++ tlh file not updating? | I have an IDL file with some interfaces in it.
[
object,
uuid(newguid),
dual,
helpstring("NewInterface Interface"),
pointer_default(unique)
]
interface INewInterface: IOldInterface
{
[id(newid), helpstring("method NewMethod")] HRESULT NewMethod([in] BSTR bstrParam );
}
But when I compile my code it d... | The .tlh and .tli file should be updated when the .tlb timestamp has changed and you're #importing it. The .tlb file is the output when compiling the .idl file. So you should check
if the compile-settings for the .idl file are correct (configuration-dependent!)
if the .tlb imported is really the same as the one comp... |
1,465,851 | 1,465,919 | Returning const reference to local variable from a function | I have some questions on returning a reference to a local variable from a function:
class A {
public:
A(int xx)
: x(xx)
{
printf("A::A()\n");
}
};
const A& getA1()
{
A a(5);
return a;
}
A& getA2()
{
A a(5);
return a;
}
A getA3()
{
A a(5);
return a;
}
int main()
{
... |
1. Is getA1() implementation correct ? I feel it is incorrect as it is returning address of local variable or temporary.
The only version of getAx() that is correct in your program is getA3(). Both of the others have undefined behaviour no matter how you use them later.
2. Which of the statements in main ( 1,2,3... |
1,465,970 | 1,465,983 | Transfer ownership within STL containers? | Is it possible to transfer ownership of a vector contents from one vector to another?
vector<T> v1;
// fill v1
vector<T> v2 = OvertakeContents(v1);
// now v1 would be empty and v2 would have all the contents of v1
It is possible for lists with splice function.
This should be possible in constant time for whole vecto... | Check out std::swap
vector<T> v1;
// fill v1
vector<T> v2;
swap(v1, v2);
OR
v2.swap(v1);
Swap Reference
|
1,466,073 | 1,466,658 | How is std::string implemented? | I am curious to know how std::string is implemented and how does it differ from c string?If the standard does not specify any implementation then any implementation with explanation would be great with how it satisfies the string requirement given by standard?
| Virtually every compiler I've used provides source code for the runtime - so whether you're using GCC or MSVC or whatever, you have the capability to look at the implementation. However, a large part or all of std::string will be implemented as template code, which can make for very difficult reading.
Scott Meyer's bo... |
1,466,121 | 1,466,152 | How to use Intel C++ Compiler with Qt Creator | I am writing a program wherein i will need to do a stupendous number of numerical calculations. But since I am developing the front end of the program in Qt Creator, I have as yet been dealing with MinGW.
As such, is there any way to integrate or use the Intel C++ Compiler with QT Creator?
Currently using IC++ 11.0 an... | I think so but you need to rebuild / reconfigure Qt Creator as documented in the Deploying an Application on Windows section. And looking into the mkspecs directory, I see 'win32-icc' which is probably what you need.
Edit: To clarify, you may need the whole 'SDK' rather than just the creator, and you need to then ... |
1,466,163 | 1,466,510 | Overridden function pointer problem at template base class C++ | I implemented a template base class for observer pattern,
template<class T>
class ActionListener
{
public:
ActionListener(void);
virtual ~ActionListener(void);
void registerListener(T* listener);
void unregisterListener(T* listener);
template<typename Signal>
void emit(Signal signal... | IEventListener::messageArrived is overloaded, so the compiler can't determine the type of &IEventListener::messageArrived. It could be void (IEventListener::*)(Message*) or void (IEventListener::*)(ClientHandle*, Message*).
The straighforward (and ugly) solution is to explicitely cast &IEventListener::messageArrived to... |
1,466,591 | 1,469,412 | Problems encountered when implement a float, translucent sub-window in MFC with C++ | I have tried several methods, but problems always exist. Sometimes the sub-window didn't refresh and sometimes the sub-window will keep blink.
This is a sample project that i have written
http://rapidshare.com/files/283950611/TestProject.7z.html
My method to implement that is:
Put a scroll bar on the top of sub-window,... | WS_EX_LAYERED only can be added to with top level window, not sub-window; I've tried to modify the window style from WS_CHILD to WS_OVERLAPPED, and then using layed window, and then clip the visiable area of the window, but, the result is not what I expected.
Anywhere, thank you for your advice...
|
1,466,756 | 1,466,769 | C++ equivalent of Java ByteBuffer? | I'm looking for a C++ "equivalent" of Java ByteBuffer.
I'm probably missing the obvious or just need an isolated usage example to clarify. I've looked through the iostream family & it looks like it may provide a basis. Specifically, I want to be able to:
build a buffer from a byte array/point and get primitives from t... | You have stringbuf, filebuf or you could use vector<char>.
This is a simple example using stringbuf:
std::stringbuf buf;
char data[] = {0, 1, 2, 3, 4, 5};
char tempbuf[sizeof data];
buf.sputn(data, sizeof data); // put data
buf.sgetn(tempbuf, sizeof data); // get data
Thanks @Pete Kirkham for the idea of generic fu... |
1,466,810 | 1,467,462 | How to draw a progress bar inside a list widget in Qt | I want to have a list of items that need to be processed in a QListWidget. Similar to Windows Media Player CD import, there should be a progress bar for every item in the list.
Now there seems to be a way to do this by creating a regular progress bar, using QPixmap::grabWidget() to save its appearance in a QPixmap and ... | Each item in a QListWidget can be represented by a QWidget of your choice, rather than the default rendering (text). You can set this by calling QListWidget::setItemWidget(). In this case, I'd recommend using QProgressBar as the rendering widget -- you should get the desired result.
From the documentation of QListWidge... |
1,466,940 | 1,467,349 | What is better for a message queue? mutex & cond or mutex&semaphore? | I am implementing a C++ message queue based on a std::queue.
As I need popers to wait on an empty queue I was considering using mutex for mutual exclusion and cond for suspending threads on empty queue, as glib does with the gasyncqueue.
However it looks to me that a mutex&semaphore would do the job, I think it contain... | A single semaphore does not do the job - you need to be comparing (mutex + semaphore) and (mutex + condition variable).
It is pretty easy to see this by trying to implement it:
void push(T t)
{
queue.push(t);
sem.post();
}
T pop()
{
sem.wait();
T t = queue.top();
queue.pop();
return t;
}
As y... |
1,467,057 | 1,468,317 | Overhead of casting double to float? | So I have megabytes of data stored as doubles that need to be sent over a network... now I don't need the precision that a double offers, so I want to convert these to a float before sending them over the network. What is the overhead of simply doing:
float myFloat = (float)myDouble;
I'll be doing this operation seve... | As Michael Burr said, while the overhead strongly depends on your platform, the overhead is definitely less than the time needed to send them over the wire.
a rough estimate:
800MBit/s payload on a excellent Gigabit wire, 25M-floats/second.
On a 2GHz single core, that gives you a whopping 80 clock cycles for each val... |
1,467,067 | 1,467,270 | Visual Studio 2008 Team: No call stack when I throw an exception | I am building the debug version of my app, with full symbols. I set a breakpoint on the following line:
throw std::range_error( "invalid utf32" );
When the breakpoint hits, my stack looks normal. I can see all my routines. But if I run, and let the exception get thrown, I see a worthless stack. it has MyApp.exe!_thread... | I think you mix up smth. here.
If you catch the exception in some catch statement or it is propagated until main your stack was unwound and you can not expect VC++ to remember the entire stack.
For example in Java stack trace is part of the exception itself. Dependent on you compiler you can write an exception class w... |
1,467,144 | 1,467,187 | How do I stop name-mangling of my DLL's exported function? | I'm trying to create a DLL that exports a function called "GetName". I'd like other code to be able to call this function without having to know the mangled function name.
My header file looks like this:
#ifdef __cplusplus
#define EXPORT extern "C" __declspec (dllexport)
#else
#define EXPORT __declspec (dllexport)
#e... | Small correction - for success resolving name by clinet
extern "C"
must be as on export side as on import.
extern "C" will reduce name of proc to: "_GetName".
More over you can force any name with help of section EXPORTS in .def file
|
1,467,449 | 1,467,500 | Designing a Vector3D class | I dont know which is the best practice when we want to create a new vector 3D class, i mean, which of this two examples is the best way ?
class Vec3D
{
private:
float m_fX;
float m_fY;
float m_fZ;
...
};
or
class Vec3D
{
private:
float m_vVec[3];
...
};
With the first apro... | use
class Vec3D
{
private:
union
{
float m_vVec[3];
struct
{
float m_fX;
float m_fY;
float m_fZ;
};
};
...
}
this will give you both at no extra cost
|
1,467,452 | 1,936,475 | QDockWidget - remove handle | Is there an easy way to remove the QDockWidget's resize handle? My dock widget can't be resized (the sizepolicy is fixed), so having the handle there is just redundant.
| This bug is as old as Qt itself, I reported this in this report for this in the Qt bugtracker. Please vote it up if you want it to get fixed faster.
|
1,467,529 | 1,467,723 | Is it possible to wrap a .net Stream as an stl std::ostream*? | I have an unmanaged c++ library that outputs text to an std::ostream*.
I call this from a managed c++ wrapper that is used by a c# library.
Currently I pass the unmanaged code a pointer to a std::stringstream and then later call System.String(stringstream.str().c_str()) to copy my unmanaged buffer back into a .net frie... | If I understood correctly, you want to wrap a .NET stream with a C++ std stream, so that your native code streams into the C++ std stream, but the data ends up in the .NET stream.
C++ IO streams roughly split into the streams themselves, which do all of the conversion between the C++ types and a binary representation,... |
1,467,538 | 1,467,876 | C++ Check if pointer is passed, else create one? | Okay i've seen this done somewhere before where you have a function that takes a pointer parameter and returns a pointer.
However you can choose not to pass a parameter and it will return a dynamically allocated pointer but if you do pass a pointer then it just fills it in instead of creating one on the heap. This is a... | You have to ask yourself why passing NULL us giving you a seg-fault. It is certainly not because NULL is not an appropriate value, it will be caused by whatever your code does when NULL is passed. However you chose not to show that code.
Haver you stepped through this code in your debugger?
Apart from that, in C++ do n... |
1,467,963 | 1,468,896 | VCL forms application writing to stdout | My company has a large Windows application with a document-object model: open application, open a file, make some changes, save, close. I'm attempting to cut the GUI off of the top and create a console application that accepts some parameters, opens a file, does something useful, saves, closes the file, and terminates... | You can write to STDOUT in a GUI program, there just usually won't be any output since there is no Console, unless it is launched from an actual Console. Alternatively, look at the GetStdHandle() and WriteConsole() functions in the Win32 API. If GetStdHandle() returns a valid handle, then you can write to it. This is... |
1,468,000 | 1,468,214 | boost scoped_lock. Will this lock? | solved
I changed the bfs::directory_iterator Queue to a std::string queue, and surprisingly solved the problem.
Hi, I have a gut feeling that i'm doing things wrong.
I've implemented (or attempted to) the thread pool pattern.
N threads read from a Queue, but i'm having some trouble. Here's what i got:
//inside a while... | The code as posted appears fine - if you're seeing problems maybe there's some other place where the lock should be taken and isn't (such as the code that adds something to the queue).
|
1,468,143 | 1,478,561 | Using QFileSystemModel in a QCompleter | How does one use QFileSystemModel in the context of a QCompleter? It looks like a better choice than QDirModel as it is non UI-blocking. The following snippet doesn't seem to do anything.
QLineEdit* l = new QLineEdit ;
QCompleter* c = new QCompleter ;
QFileSystemModel* m = new QFileSystemModel ;
m->setRootPath( "c:\\" ... | Looks like it just hasn't been implemented yet.
http://qt.nokia.com/developer/task-tracker/index_html?method=entry&id=221860
|
1,468,165 | 1,468,231 | How to send a CBN_SELCHANGE message when using CB_SETCURSEL? | When using the CB_SETCURSEL message, the CBN_SELCHANGE message is not sent.
How to notify a control that the selection was changed ?
P.S.
I found on the Sexchange site, a very ugly hack :
SendMessage( hwnd, 0x014F/*CB_SHOWDROPDOWN*/, 1, 0 );
SendMessage( hwnd, 0x014E/*CB_SETCURSEL*/, ItemIndex, 0 );
SendMessage( hwnd,... | You're not supposed to use CBN_SELCHANGE unless the change in selection was made by the user.
You don't indicate what language you're using; it would make it easier to provide you with a workaround if you did so.
In Delphi, where an OnChange() would be associated with the combobox, you just call the event method direct... |
1,468,298 | 1,474,397 | Is there any way to access all of the Clib functions from one file? | I'd like to include just one file instead of all of them, because the compiler I have to use does not include them by default.
| Write a header that includes all standard headers and include it in your file. That would make compilation slow though.
|
1,468,662 | 1,489,278 | OpenCV Vs ImageMagick? | I have an upcoming project which is about image segmentation i.e. to group the pixels constituting the image into clusters based on certain visual properties of the pixel.
We plan to do it in C++ and have zeroed in on two image processing/manipulation libraries - OpenCV and ImageMagick. I'm reading on ImageMagick and i... | I've used OpenCV for this type of task and have found it to work very well. It's well documented and has many of the types of operations that one typical needs for image analysis. I don't see how ImageMagick could even get you started on this.
I'm assuming here that what you mean by "image segmentation" is grouping p... |
1,468,774 | 1,468,817 | Why am I having problems recursively deleting directories? | I've written an application that uses the WIN32 api to create a temporarily directory hierarchy. Now, when wanting to delete the directories when shutting down the application I'm running into some problems.
So lets say I have a directory hierarchy: C:\temp\directory\subdirectory\
I'm using this recursive function:
bo... | You're not closing dhandle from all those FindFirstFile calls, so each directory has a reference to it when you try to delete it.
And, why do you need to create DirectoryHandle? It's not needed, and will probably also block the directory deletion.
When your app closes, those handles are forced close, and (I guess) the... |
1,469,033 | 1,469,089 | How to initialize an array in a class constructor? | Working in Xcode on Mac OS X Leopard in C++:
I have the following code:
class Foo{
private:
string bars[];
public:
Foo(string initial_bars[]){
bars = initial_bars;
}
}
It does not compile and throws the following error:
error: incompatible types in assignment of 'std::string*' to 'std::string [0u... | Arrays behave like const pointers, you can't assign pointers to them. You also can't directly assign arrays to each other.
You either
use a pointer member variable
have a fixed size of bars you get and initialize your member array with its contents
just use a reference to a std container like std::vector
|
1,469,149 | 1,469,166 | Calculating vertices of a rotated rectangle | I am trying to calculate the vertices of a rotated rectangle (2D).
It's easy enough if the rectangle has not been rotated, I figured that part out.
If the rectangle has been rotated, I thought of two possible ways to calculate the vertices.
Figure out how to transform the vertices from local/object/model space (the on... | I would just transform each point, applying the same rotation matrix to each one. If it's a 2D planar rotation, it would look like this:
x' = x*cos(t) - y*sin(t)
y' = x*sin(t) + y*cos(t)
where (x, y) are the original points, (x', y') are the rotated coordinates, and t is the angle measured in radians from the x-axis.... |
1,469,211 | 1,469,243 | Unmanaged dll call to crash a dotnet app? | As part of segmenting my app into separate appdomains in order to catch and recover from an intermittent crash when calling a native dll, I need a way to reliably trigger this type of crash in order to determine if I am catching the appdomain going down correctly.
I'm looking for some simple native code (C++ ?) I can c... | Just make a native C++ function that does anything bad, such as divide by zero, ie:
void BeABadMethod()
{
int i = 5;
int j = 0;
printf("%d", i/j);
}
|
1,469,370 | 1,469,445 | Why can't I import the 'math' library when embedding python in c? | I'm using the example in python's 2.6 docs to begin a foray into embedding some python in C. The example C-code does not allow me to execute the following 1 line script:
import math
Using line:
./tmp.exe tmp foo bar
it complains
Traceback (most recent call last):
File "/home/rbroger1/scripts/tmp.py", line 1, in <m... | I'm using Python 2.6, and I successfully compiled and ran that same example code that you listed, without changing anything in the source.
$ gcc python.c -I/usr/include/python2.6/ /usr/lib/libpython2.6.so
$ ./a.out random randint 1 100
Result of call: 39
$ ./a.out random randint 1 100
Result of call: 57
I specifica... |
1,469,635 | 1,469,644 | SDL: Initializng TTF problems. Possibly freetype? | Edited: Look at comments below. Short version: Screen simply flashes when I try to run program.
int main(int argc, char** args)
{
bool quit = false;
std::ofstream out("error.txt");
if(init() == false)
{
return 1;
}
if (load_files() == false)
{
return 1;
}
// Rend... | What's the problem you're having? Is it failing to compile? Failing to link? Failing at program load time due to missing DLLs/shared libraries? Or failing at runtime?
Is screen NULL after the call to SDL_SetVideoMode()? If so, you should print out SDL_GetError(). If it is in fact TTF_Init() that is failing, then ... |
1,469,687 | 1,469,748 | Lookup table where most sequential values point to the same object? | Suppose I have a range of keys, say 0 -> 1000
Say 0 - > 99 map to one object
100 -> 251 map to another
etc.
etc.
What is a good way to map a key to an object without having to have an array of 1000 size and a bunch of if (x >= 0 && x <= 99) business?
I mean without any logic i.e. a stairstep table
| Use a std::map along with lower_bound:
map<long, string> theMap;
theMap[0] = "lessThan1";
theMap[99] = "1to99";
theMap[1000] = "100to1000";
theMap[numeric_limits<long>::max()] = "greaterThan1000";
cout << theMap.lower_bound(0)->second << endl; // outputs "lessThan1"
cout << theMap.lower_bound(1)->second << endl; // out... |
1,469,743 | 1,469,766 | Standard Library Containers with additional optional template parameters? | Having read the claim multiple times in articles - I want to add this question to Stackoverflow, and ask the community - is the following code portable?
template<template<typename T, typename Alloc> class C>
void f() {
/* some code goes here ... */
}
int main() {
f<std::vector>();
}
Is the implementation that sup... | I found the following issue report, which says
There is no ambiguity; the standard is clear as written. Library implementors are not permitted to add template parameters to standard library classes. This does not fall under the "as if" rule, so it would be permitted only if the standard gave explicit license for imple... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.