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
7,078,424
7,079,172
Check if it is an integer
I have the problem that I must read Integers from a database. The varibles are returned as Strings and can be "", "0", "1", "2" or "3" (these are the ones I've seen so far). So using the standard atoi function doesn't help because then I can't differentiate between "" and "0". Does somebody have a good solution to sol...
If performance is an issue in your case, I propose the followings: Solution 1: std::string input(<your string value>); int val; if (sscanf(input.c_str(), "%d", &val) != 1) { cout << "it's empty/not an integer"; } else { cout << "val is:" << val; } Solution 2: std::string input(<your string value>); int val; if...
7,078,470
7,112,613
Problems trying to compile a program with external header
I'm learning c++ and I'm trying to use a library that I've downloaded from internet in my program ( from here https://mattmccutchen.net/bigint/). Because I want everything to be quite tidy, I put all the .hh files in a subfolder named "BI". However when I try to compile my .cpp file with g++ (It's MinGW on Windows XP S...
Ok, so after some messing around I figured out that I needed to do a couple of things add the -L switch with the dir of the header files add to the g++ command line all the .cc files (e.g. g++ test.cpp BigInteger.cc etc.) put everything in a batch file for semplicity wow, now it seems quite easy!
7,078,511
7,079,859
Usage example of boost::condition::timed_wait
Does someone have an example of how to most easily use boost::condition::timed_wait? There are some threads on the topic here, here and here, but none feature a working example. And boost doc is as usual quite sparse.
Actually, I finally found a link with full example here. With a bit of adapting, this seems to be the call. boost::system_time const timeout=boost::get_system_time()+ boost::posix_time::milliseconds(35000); boost::mutex::scoped_lock lock(the_mutex); if(the_condition_variable.timed_wait(lock,timeout,&CondFulfilled)) { ...
7,078,521
7,097,538
Write date/time value to registry
What's the best data type and/or format to write and read a date and time value in the Windows Registry? I'm using C++ with MFC and working with CTime and CTimeSpan objects, but I feel comfortable using the CRT library as well. My understanding is that to correctly represent a time value, a 64-bit integer should be use...
Use CTime::GetTime, and store the returned 64-bit integer into registry. When loading pass the same integer to CTime constructor. You may also consider using time functions.
7,078,553
7,081,239
Uninitialized class fields and STL containers
Does STL default allocator zero raw memory before placing objects into it? See this code. The comments reflect the behavior on my platform. #include <iostream> #include <vector> struct Foo { Foo() {} // n isn't initialized int n; }; int main() { std::vector<Foo> v(2); // zeroed std::cout << v[0].n <<...
A container will default-initialize the objects it creates if you don't give them a specific value. In your case the default constructor for the object does not initialize the POD integer, so it will contain whatever was left over in memory. Sometimes new heap blocks will be zero initialized by the OS, but you can't ev...
7,078,571
7,079,313
unpacking, function application, and packing tuples in C++0X
What is the best way to write the readvals function in the following code without using Boost? Basically, it should get a tuple, call a specific function of it's elemets and return the generated results as a tuple again. Is there any C++0X-based Functor definition library for tuples? template <class T> struct A { A...
Is this what you are looking for? I hope you can at least use it as a starting point. There are just more ways to approach working with tuples and variadic templates than there are ways that lead to rome... #include <iostream> #include <tuple> template<class T> struct A { T t; A( const T& t_ ) : t(t_) { } }; ...
7,078,576
7,078,965
Template simplification
In one of my projects, I have the following class template hierarchy : template <typename FruitType, typename ParentFilterType = void> class filter; template <typename FruitType> // Specialization when no parent filter is needed class filter<FruitType, void>; Where FruitType can be anything. Let's say it is one of ap...
In C++0x, it would be variadic template. Without C++0x, you can simply use a large list of parameters, with defaults supplied. template <typename F0, typename F1 = void, typename F2 = void, typename F3 = void> struct complex_filter { typedef filter<F0, typename complex_filter<F1, F2, F3>::type> type; }; template <> ...
7,078,785
7,078,955
Design Problem: Thread safety of std::map
I am using std::map to implement my local hash table, which will be accessed by multiple threads at the same time. I did some research and found that std::map is not thread safe. So I will use a mutex for insert and delete operations on the map. I plan to have separate mutex(es), one for each map entry so that they can...
You will in deed need to put find in a critical section, but you might want to have two different locks, one for writing and one for reading. The write lock is exclusive but if no thread holds the write lock several threads may read concurrently with no problems. Such an implementation would work with most STL implemen...
7,078,842
7,078,900
STL map instantiating
have next code: class GameTexture { private: LPDIRECT3DTEXTURE9 texture; unsigned char *alphaLayer; UINT width, height; GameTexture() {}; GameTexture(const GameTexture&) {} public: static GameTexture *CreateTexture(LPCTSTR pSrcFile, LPDIRECT3DDEVICE9 d3dDevice); ~GameTexture(); }; class TexturesPool { private: map<...
It's possible that you're missing #include <string> which is where the missing operator< should be declared. Some of MSVC's headers forward-declare std::string, but do not actually include <string> itself.
7,078,860
7,079,147
Iterate over range, and "one more"
In the algorithm I'm currently implementing, there is this line (where u is a vertex in a graph, and Pred(u) are all vertices having edges pointing at u): for all s ∈ Pred(u) ∪ {u} The Pred(u) part I translate into boost::graph code like this: boost::graph_traits<Graph>::in_edge_iterator in_begin, in_end; boost::tie(i...
I think the solution you are using is alright (as long as the Do stuff code is well factorized). However, if you often face such issues, you can have a look at Boost.Range, a library for manipulating ranges of values instead of iterators. Here, you could use the join function to obtain the union of your two ranges (the...
7,078,935
7,080,028
Gaussian Blur with FFT Questions
I have a current implementation of Gaussian Blur using regular convolution. It is efficient enough for small kernels, but once the kernels size gets a little bigger, the performance takes a hit. So, I am thinking to implement the convolution using FFT. I've never had any experience with FFT related image processing so ...
The 2-D FFT is seperable and you are correct in how to perform it except that you must multiply by the 2-D FFT of the 2D kernel. If you are using kissfft, an easier way to perform the 2-D FFT is to just use kiss_fftnd in the tools directory of the kissfft package. This will do multi-dimensional FFTs. The kernel size...
7,079,230
7,079,411
Bad Use Of Templates?
I understand that templates kinda get blamed for binary bloat, I also understand that a template is just a pattern. I dont really understand the nuts and bolts as it where. Alot of time I see code like the following where it returns a base class pointer. class GameObject { public: Component* getComponent(std::stri...
The fact that the method takes the "key" which appears to be really a type (the type of component to return) indicates to me that the type is not really known until runtime. If that's the case then a compile time mechanism like templates will not do. The only option is to return a base class pointer. And typically whe...
7,079,376
7,079,426
Please enlighten on the following C++ Syntax and its sense! (probably a case of overloading)
I am going through a legacy, and found the following syntax of C++ to be strange: the class definition follows as: class thread_shared : public master { public: thread_shared() { thread_id = 0; } int thread_id; std::string title; std::string (*text2html)(std::string const &); // What's...
std::string (*text2html)(std::string const &); // What's this declaration? That is a function pointer definition. It declares a variable text2html to be a pointer to a function with the signature std::string (std::string const &). c.text2html = text2html; // whats this?? That is setting the pointer to refer to the...
7,079,819
11,939,800
WinPcap Block Packets
Is there a way that, using WinPcap, I can read a packet and if that packet is going to a certain domain name, I can block the packet with a custom HTML page? Like, if I wanted to go to myspace and my program saw that, is there a way I could return HTML saying "Site Blocked"?
WinPcap provides the capability for sending packets, so using this capability you can terminate a tcp session by preparing a packet with the IP address and port numbers of the offending packet with the FIN flag ON and then send the packet to the server so that it closes the session and send it(with modification) to the...
7,079,950
27,639,619
Tools to detect False Sharing in a C/C++ application
Are there any tools that detect and report False Sharing for applications written in C or C++?
Try Sheriff and Predator. Sheriff is at https://github.com/plasma-umass/sheriff, while Predator is at https://github.com/plasma-umass/Predator. Predator is a compiler-based approach that you have to recompile your program using a new LLVM compiler. It is the most exhaustive detection tool up to now. Sheriff is librar...
7,079,990
7,080,227
Redirect the stdout to buffer,not using >
I wrote my implementation of printf – myPrintf,which prints to stdout. I want to verify that it works fine.In order to check the correctess of the printed output I want to compare it with char I expect to get. How can I write code to redirect the stdout to buffer,not using >. I can use only printf!
You could redirect couts buffer by setting it's rdbuf() to a file you have opened. Weird, C++ and only printf, but whatever. It's also possible to redirect stdout in C. Here is one way of doing it: https://rydow.wordpress.com/2007/10/26/c-code-to-redirect-stdout/ It involves dup and dup2. There is also this option ( Re...
7,080,014
7,080,518
Measuring the resolution of `std::clock()`
Is it possible to measure the resolution of the std::clock() call? Or is this a problem where observing without influencing isn't possible? I wrote the following naive benchmark: #include <ctime> #include <iostream> int main() { std::clock_t initial = std::clock(); std::clock_t current; while (initial == (...
You can, sort of. Something like what you're doing is a good first approximation. But I'm not sure how useful it is: it determines the resolution, but it still doesn't tell you anything about the accuracy; under Windows, for example, clock is so inaccurate as to render it useless.
7,080,137
7,081,061
reusing the copy-and-swap idiom
I'm trying to put the copy-and-swap idiom into a reusable mixin: template<typename Derived> struct copy_and_swap { Derived& operator=(Derived copy) { Derived* derived = static_cast<Derived*>(this); derived->swap(copy); return *derived; } }; I intend it to be mixed in via CRTP: struc...
I am afraid this is one area where a macro is necessary, because of the complex rules about automatically generated copy and assignment operators. No matter what you do, you are in either of two cases: You have provided (explicitly) a declaration of the assignment operator, in which case you are expected to provide a ...
7,080,256
7,080,300
Why are references to const necessary to avoid copying parameters
According to Wikipedia, function calls don't copy parameters which are are references to a const type: void f_slow(BigObject x); void f_fast(const BigObject& x); f_slow(y); // slow, copies y to parameter x f_fast(y); // fast, gives direct read-only access to y Why does the reference need to be const? Wouldn't a non...
Yes, any kind of reference will do. Making it const makes it more flexible as it can accept const variables or temporaries as parameters, and documents (and enforces) your intent not to modify the parameter.
7,081,176
7,081,315
One reader. One writer. Some general questions about mutexes and atomic-builtins
I have a parent and a worker thread that share a bool flag and a std::vector. The parent only reads (i.e., reads the bool or calls my_vector.empty()); the worker only writes. My questions: Do I need to mutex protect the bool flag? Can I say that all bool read/writes are inherently atomic operations? If you say Yes or ...
Do I need to mutex protect the bool flag? Not necessarily, an atomic instruction would do. By atomic instruction I mean a compiler intrinsic function that a) prevents compiler reordering/optimization and b) results in atomic read/write and c) issues an appropriate memory fence to ensure visibility between CPUs (not n...
7,081,283
7,081,377
How to find ip addresses with BSD sockets?
I am using BSD sockets over a wlan. I have noticed that my server computer's ip address changes occasionally when I connect to it. The problem is that I enter the ip address into my code as a literal string. So whenever it changes I have to go into the code and change it there. How can I change the code so that it will...
Use a domain name that can be looked up in your hosts file or in DNS, rather than an IP address.
7,081,367
7,081,484
Printing universal characters
Can anyone explain why universal character literals (eg "\u00b1") are being encoded into char strings as UTF-8? Why does the following print the plus/minus symbol? #include <iostream> #include <cstring> int main() { std::cout << "\u00b1" << std::endl; return 0; } Is this related to my current locale?
2.13.2. [...] 5/ A universal-character-name is translated to the encoding, in the execution character set, of the character named. If there is no such encoding, the universal-character-name is translated to an implementation defined encoding. [Note: in translation phase 1, a universal-character-name is introdu...
7,081,370
7,081,445
What is the proper term for non-function-pointers in C++?
In C++ you can pass in "function types", which are like function pointers but they are just the type of the function and not a pointer to it. For example: template< typename T > class MyTemplateClass { // ... }; // ... and later... MyTemplateClass<void (int, int)> mtc; What is the proper name for this form? Is th...
Yes, the term is "function type".
7,081,406
7,086,105
Force gstreamer appsink buffers to only hold 10ms of data
I have a gstreamer pipeline which drops all of its data into an appsink: command = g_strdup_printf ("autoaudiosrc ! audio/x-raw-int, signed=true, endianness=1234, depth=%d, width=%d, channels=%d, rate=%d !" " appsink name=soundSink max_buffers=2 drop=true ", bitDepthIn, bitDepthIn, cha...
I got rid of the autoaudiosrc and plugged in alsasrc instead. The pulsesrc plugin was what was causing the erratic blocking behavior on the buffer pull which was giving me varying buffer lengths. The only problem then was that alsasrc wouldn't capture in mono. I remedied that by adding in an audioconvert element to the...
7,081,513
7,083,771
Polymorphic pointer to member variables
I'm trying to use pointers to member variables in a polymorphic fashion. This works: struct Foo { int member0; int member1; int* getMember( int i ) { static int Foo::* table[2] = { &Foo::member0, &Foo::member1 }; return &( this->*table[i] ); } }; This does not, since the members are not of th...
This is not possible. Because of multiple inheritance, address-of-base is not always the same as address-of-derived. You need some hidden address adjustment magic to convert one to the other, and a pointer-to-member, being a very simple object (basically an integer offset) cannot accomodate this magic. It is true that...
7,081,610
7,081,651
Strange behaviour of boost::function with function pointers
I was playing around with boost::function when I stumbled across the following issue. typedef int(*IFnPtr2)(Interface*,int,bool&); IFnPtr2 p = NULL; boost::function<int(Interface*,int,bool&)> fn; // this is fine boost::function<IFnPtr2> fn2; // this gives me a compile error I was wondering why function is behaving dif...
Use a function type for the template parameter to boost::function, not a function pointer type: typedef int function_type(Interface*,int,bool&); function_type* p = 0; // Pointer to function here boost::function<function_type> fn;
7,081,725
7,086,784
Terminating unicode null character
I have an array of wchar_t. I need to add a unicode null character at a specific position in the array. wchar_t var1[100]; var1[79] = '\u0000'; I tried the above but get the following compilation error. error C3850: '\u0000': a universal-character-name specifies an invalid character How do I add a unicode null chara...
The language doesn't allow you to use universal character names for characters that you can easily write without using a UCN. That's why '\u0000' isn't permitted. (I'm not quite sure what the rationale for that rule is.) Since var1 is an array of wchar_t, L'\0' is the most straightforward thing to use. But since char...
7,081,770
7,082,169
specifying which adapter wininet will use
I have a Visual Studio 2008 C++ application that uses WinInet to retrieve files from HTTP and FTP servers. Is there a way I can specify which network adapter WinInet will use to connect to the remote servers or specify which IP address will originate the connection?
I think the short answer is that you cannot. WinInet doesn't expose most of the lower-level (Winsock) functionality that you'd need to accomplish this. I know that Winsock does allow more control over the network interfaces/adapters, but then you'd have to decide on a way to make the HTTP/FTP requests beyond that.
7,081,820
56,490,401
Setting default compiler in CMake
I'm using CMake version 2.8 on WinXP SP3. Whenever i run my CMakeLists script by default CMake use Visual Studio 10 compiler. I've tried to do: SET( CMAKE_CXX_COMPILER "C:/MinGW/bin/g++" ) without success. How can i set MinGW as my default compiler so that i do not have to worry about setting compiler in the CMakeList...
With CMake version 3.15 or later, you can set the CMAKE_GENERATOR environment variable to specify the default generator to be used on your system.
7,081,851
7,081,941
Why is this "invalid C++"
I was reading intro on gtest and found this part confusing: The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? If your class has a static data member: // foo.h class Foo { ... static const int kBar = 100; }; You als...
First things first, inside a class body is not a definition, it's a declaration. The declaration specifies the type and value of the constant, the definition reserves storage space. You might not need the storage space, for instance if you only use the value as a compile time constant. In this case your code is perfect...
7,082,175
7,082,201
const char myVar* vs. const char myVar[]
Possible Duplicate: Difference between using character pointers and character arrays What's the difference between: const char* myVar = "Hello World!"; const char myVar[] = "Hello World!"; If there is one?
The pointer can be reassigned, the array cannot. const char* ptr = "Hello World!"; const char arr[] = "Hello World!"; ptr = "Goodbye"; // okay arr = "Goodbye"; // illegal Also, as others have said: sizeof(ptr) == size of a pointer, usually 4 or 8 sizeof(arr) == number of characters + 1 for null terminator
7,082,227
7,082,471
Persistent IPC between Bash script and C++
Problem: There is a C application that calls a Bash script each time an event happens. And there is also a C++ application that needs to track down those events. The C++ application is driven by a select() event loop. What would be the most simplest IPC to implement between Bash script and C++ application? C Applicatio...
Unix datagram or UDP socket would do. The bash script would just send a datagram to that socket (you may need a helper program that does sendmsg() or sendto() on that socket, such as socat or netcat/nc). The receiver does not need to accept connections for datagram sockets, once it is ready for read there must be a dat...
7,082,234
7,082,411
C++ DLL crashes when calling from managed code
there's a WinForms-application written in C# using .NET Framework 3.5. This application uses a C++ Dll which is imported using the following declaration: [DllImport(DllName)] public static unsafe extern int LoadDBData(String dsn, String userid, String password); This method imports data from a given ODBC-DSN using a S...
This seems like a problem with the vendor's library, rather than your code. Managed and unmanaged memory should be considered to be completely separate. Managed memory is typically memory allocated on a garbage-collected heap, while unmanaged memory is anything else: the ANSI C memory pool allocated through malloc...
7,082,261
7,082,413
How do I add foreach iteration support to my own collection class in C++?
I have created a C++ implementation of a collection type. I would like to add iteration support so that developers may use the "for each" statement on it. How can I do that?
The standard idiom is : expose types iterator and const_iterator and provide minimum two functions namely, begin() and end() as: template</*.....*/> class Collection { public: typedef /*...*/ iterator; typedef /*...*/ const_iterator; iterator begin(); iterator end(); const_iterator begin() c...
7,082,349
7,082,493
Applicability of Deterministic Languages
New deterministic languages are arising on the scene for deterministic execution of mulithreaded software running on multicore, such as Cilk++ and Deterministic Parallel Java. Now my question is, can these languages be used to implement any type of algorithm or only specific ones. In other words, do these languages li...
Most common definitions of "algorithm" do not allow an algorithm to specify a computation that cannot be performed by a Turing machine. Assuming you are using one of those conventional definitions, No. All Turing machines can be specified (modulo resource limits) in a Turing complete language. These deterministic la...
7,082,352
7,082,437
Derived Class not Calling Entire Base Constructor
I'm sure this is just some stupid syntax error I'm making, but when my class CNeck derived from CLimb calls its default constructor, CNeck() everything works as expected. When it calls a different constructor CNeck(*parent) it seems to call about half of the specified base constructor, then gives uses the compiler defa...
Your constructor is marked CLimb(CLimb *_parent); meaning it takes a pointer to a CLimb but in the CNeck constructor, CNeck::CNeck(CLimb *_parent) : CLimb(*_parent) you're dereferencing the pointer, which calls CLimb(CLimb&) which is the copy constructor. Turn *_parent into _parent to resolve this problem. Plus you mi...
7,082,612
7,089,434
How to avoid interfering namespace issues between the Juce Framework and OpenCV?
I created an Juce Audio-Plugin project with the introjucer and Xcode4. All works fine until I added #include <cv.h> into my code. I got 317 issues in the OpenCV files: core.hpp, operations.hpp, mat.hpp, imgproc.hpp, features2d.hpp, objdetect.hpp that 'juce::Point' is not a type and some other namespace errors... I trie...
Solved the problem for the moment: I have added all opencv include instructions at the top of the PluginEditor.cpp. But I have a new problem: Compile issues with OpenCV and Juce on Xcode4.1 in 32bit on Lion.
7,082,691
7,082,728
zeroing derived struct using memset
I want to zero out all members of a derived structure. There are hundreds of members and more are added every once in a while so I feel that initializing them explicitly is error-prone. The structures have no virtual functions and all the member fields are built-in. However, they are not POD by virtue of having non-tr...
This assumes that the Base base class subobject is located at the beginning of Derived. This won't work if you add another base class. Further, your code is wrong: pointer arithmetic is performed in terms of objects, not in terms of bytes. You need to use reinterpret_cast<char*>(this) to perform the arithmetic in te...
7,082,786
7,082,882
Char Array VS Char *
This is a question based on answers from question: const char myVar* vs. const char myVar[] const char* x = "Hello World!"; const char x[] = "Hello World!"; I understand the difference now, but my new questions are: (1) What happens to the "Hello World" string in the first line if I reassign x? Nothing will be point...
Placing "Hello World!" in your code causes the compiler to include that string in the compiled executable. When the program is executed that string is created in memory before the call to main and, I believe, even before the assembly call to __start (which is when static initializers begin running). The contents of c...
7,082,837
7,085,076
Changing Thread Task?
I know you cannot kill a boost thread, but can you change it's task? Currently I have an array of 8 threads. When a button is pressed, these threads are assigned a task. The task which they are assigned to do is completely independent of the main thread and the other threads. None of the the threads have to wait or any...
A thread is not some sort of magical object that can be made to do things. It is a separate path of execution through your code. Your code cannot be made to jump arbitrarily around its codebase unless you specifically program it to do so. And even then, it can only be done within the rules of C++ (ie: calling functions...
7,082,860
7,083,037
fastest way to do keyword search in large text in C/C++
Say I have 100 keywords (that can include spaces) and I need to find out how many times they occur in a big piece of text. What would the fast way be to accomplish this? My current idea is as follows: turn the keywords into a suffix tree walk through the text following the nodes and whenever a char does not occur (i.e...
The problem with the suffix tree approach is that you have to start the suffix search for each letter of the text to be searched. I think the best way to go would be to arrange a search for each keyword in the text, but using some fast search method with precomputed values, such as Boyer-Moore. EDIT: OK, You may be s...
7,082,963
7,083,009
C++ compiler picking the wrong overload of a class member function
I have this code: template <class T> class Something { T val; public: inline Something() : val() {} inline Something(T v) : val(v) {} inline T& get() const { return val; } inline Something& operator =(const Something& a) { val = a.val; return *this; } }; typedef Something<int> IntSomething; typede...
o is not const-qualified, so the non-const some_function is selected. If you want to select the const-qualified overload, you need to add the const qualifier to o: Other o; Other const& oref(o); ConstIntSomething s; s = oref.some_function(); When overload resolution occurs, the compiler only looks at the o.some_funct...
7,083,205
7,083,379
Can I set a compile time flag to include a header?
I have a configuration class that I would like to use for a variety of builds. The class itself changes between builds, but the class name remains the same, as does the header file name. The separate versions of this class are held in separate subfolders. ex. main/config.h main/config.cpp secondary/config.h seconda...
Depending on what build system you are using you would create a variable that points to the main or secondary path. This variable is then used to append to the INCLUDE path so all of your sources can just #include "config.h" when they need access to config. In your Makefile (or equivalent) you will need to add the $CON...
7,083,463
7,083,555
Change Terminal Font Size with C++
I'm doing a small project for fun in C++ (in Ubuntu 11.04) and the program is text-based (all in the Gnome terminal). I'm using the ncurses library to change the font color, but I also want to print different sized text to the terminal, and can't figure out how to do that with ncurses. Is there a way to do this (perhap...
At least for xterm, you can change the current font by printing an escape sequence. The syntax is ESCAPE ] 50 ; FONTNAME BEL. Here's (an abbreviated version of) a script I use for this; I call it xfont (the real one has more error checking): #!/usr/bin/perl use strict; use warnings; print "\e]50;@ARGV\a"; I don't k...
7,083,612
7,083,675
defining a static variable of base class
I have a class structure : A <- B where A is base class and B is the derived one. Some independent code creates object of both these classes. A has a static variable (lets say 'static_a') which is used in A as well as B. Where should I define this static_a ? When I define that in A.h, it gives me linker error saying ...
A static variable definition is a little like declaring an extern variable or a function prototype. It lets the linker know the variable or function exists somewhere in all the compilation units, but it does not create the variable, it just says that it will exist somewhere. It doesn't make the variable exist. When you...
7,083,830
7,083,904
Is there a shorter way of writing `StringPtr ? StringPtr : "null"`?
I have this code: std::wstringstream outstream; outstream << (prop.m_pwszOriginalVolumeName ? prop.m_pwszOriginalVolumeName : L"null") << L";" << (prop.m_pwszSnapshotDeviceObject ? prop.m_pwszSnapshotDeviceObject : L"null") << L";" << (prop...
You could define a small function: whatever_t strOrNull(whatever_t str) { return str ? str : L"null"; } Then your code becomes std::wstringstream outstream; outstream << strOrNull(prop.m_pwszOriginalVolumeName) << L";" << strOrNull(prop.m_pwszSnapshotDeviceObject) << L";" << strOrNull(prop.m_...
7,083,963
7,084,097
Strange behavior of this simple pthread code
If I'll compile and run the code below 1 #include <iostream> 2 #include <pthread.h> 3 #include <cstdio> 4 #include <cstdlib> 5 6 #define NTHREADS 4 7 #define N 100 8 #define MEGEXTRA 1000000 9 10 using namespace std; 11 12 pthread_attr_t attr; 13 14 void *doWork (void *threadid) { 15 double...
That's because the main thread, the one that creates the others, exits (by the vertue of pthread_exit - and you're getting at the end of mainanyway) before all the created threads had the time to run. The i array gets destroyed and contains garbage at the time it is read by all the threads. You have to wait - i.e. pthr...
7,084,135
7,084,198
What does this error mean?
I am writing a C++ code in the ROOT platform. I am getting the following error: *** Break *** segmentation violation gdb not found, need it for stack trace Root > Function main() busy flag cleared I just want to know what this means (in general).
Typically that means you have written to (or maybe read) memory you don't have permission on. Either it's just invalid memory or (if the platform supports such a concept) it's outside of the memory you own. A common cause of this is freeing a pointer but then using it again. Foo * pFoo = new Foo(); pFoo->Bar(); // shou...
7,084,347
7,084,438
When to call PostQuitMessage
Like many applications, mine creates multiple windows. I do not know and cannot keep track of how many windows have been created, so I don't know when there are none. My problem is that when all the windows are closed, unless I call PostQuitMessage somehow, the application keeps running with no windows open (obviously)...
Just keep a static variable with a count of the number of open windows. When a windows opens have it increment the counter; in the WM_DESTROY handler decrement it. When the count goes to zero, call PostQuitMessage.
7,084,741
7,084,768
Less-Than Vs. Equal-To For Efficiency C/C++
When I've used older APIs, for example, the C sockets API on Unix, I always notice that people favor less-than (<) over equal-to (==) when comparing their bad return values. int result = send(...); if (result < 0) { perror("..."); } In the cases I'm referring to, the return code is only ever positive, 0, or -1 (with e...
I think that this is neither for habit nor for efficiency. It is safer because you don't rely on a specific return code. Instead, you rely for the error code to be negative. For instance, strcmp function returns "a negative value" when the first string is smaller than the second. On most implementations, it will return...
7,084,780
7,085,370
Using a std::vector<char> as a variant
I want a simple variant with minimal overhead that can be passed to functions written in the C language so I decided to use a std::vector like this typedef std::vector<char> SimpleVariant; SimpleVariant data; (1) store a std::string for(std::string::iterator it = str.begin(); it != str.end(); ++it) { da...
You haven't really given much information about how the C interface to this works. So this suggestion may not be helpful. But let's assume you have a C interface that looks like this: int GetAValue(void *data, int size); //Returns the type of data stored in the data pointer. Will not write past size. void DoSomethingWi...
7,084,831
7,085,249
Difference between default-initialize and value-initialize in C++03?
I had always thought that creating a new object would always call the default constructor on an object, and whether the constructor was explicit or automatically generated by the compiler made no difference. According to this highly regarded answer to a different question, this changed in a subtle way between C++98 and...
I do not know what the rationales around the change (or how the standard was before), but on how it is, basically default-initialization is either calling a user defined constructor or doing nothing (lots of hand-waving here: this is recursively applied to each subobject, which means that the subobjects with a default ...
7,084,949
7,085,109
Linker undefined symbols error
It seems like my two files, userinterface.h #ifndef USERINTERFACE_H #define USERINTERFACE_H #include <string> #include "vocabcollection.h" namespace user_interface { //Finds a file // //Returns when user selects a file std::string findFile(); //more comments followed by functions } #endif and userinterface.cpp, #i...
In the header file, you declare the function findFile in the namespace user_interface. In the cpp file the free function findFile is defined. Yes, you are using namespace user_interface, but the compiler doesn't know that the findFile defined there belongs to namespace user_interface. The result of all this is that you...
7,085,203
7,085,377
Categorizing items the right way
I'm working on an application which among other things downloads items that belong to a certain category form a server. I want to make the downloader look like this: class Downloader { Downloader(const ItemCategoryBase &category); ... } Each class derived from ItemCategoryBase will provide it's category ID tr...
If you really have determined that this is the right way to do things, then I would suggest writing a code generator to handle it for you: create a CSV document containing all the Category ID's, and write an app that inserts each ID into template header/source files, and saves it out.. (For instance, put "$CATEGORY_ID"...
7,085,392
7,085,531
How to make a Font and use it
I recently saw that when sfml loads a font from memory by receiving a const char*. How does this represent a font? I also saw the arial.hpp file only contains a huge array of numbers(chars), which you can feed into the LoadFont function. the font class in SFML also holds an image, but I don't know how it gets set sin...
As far as I can tell, there is no LoadFont function in SFML. There are Font::LoadFromFile and Font::LoadFromMemory. I'll assume you're talking about those. From the documentaiton for Font::LoadFromMemory: Load the font from a file in memory. It is for cases when you have loaded something into memory. That is, if you'...
7,085,421
7,085,451
Stack around the variable 'equation' was corrupted
I'm trying to make a calculator in VC++ and even though it runs, it keeps reading memory that I haven't told it to, and I don't know how to make it stop. #include <iostream> #include <ctype.h> int main(){ char equation[4]; equation[3] = '\0'; //string terminator int result; bool wantsToContinue = true; char yesOrNo; ...
You make it stop by not writing an arcane Frankenstein language mix of C and C++, but instead using real C++ string types: #include <string> #include <istream> #include <iostream> int main() { std::string equation; std::cin >> equation; // now equation[0] is the first character } Note that int(equation[0]) is...
7,085,619
7,086,444
How are QGLWidget's glXXX function calls handled?
How does Qt handle the function calls to various OpenGL functions such as glVertex3f in a QGLWidget? Are these calls part of the QGLWidget object or are they strictly the global namespace OpenGL functions? What is the best practice for drawing on a QGLWidget from a separate class?
Those gl… functions are just the regular OpenGL functions, or if a extension wrapper is being used the macro names resolving to the wrapper's symbols. QGLWidget takes care of OpenGL context creation and management, just like GLUT or GLFW do. QGLWidget offers the member function QGLWidget::makeCurrent which selects the ...
7,085,745
7,086,285
Malloc on a struct containing a std::vector
Here is the situation : I use a malloc to allocate memory for a struct. The struct contains various items such as pointers, string variables and vectors. The fact is, when we use malloc, no constructors are called. Using a code similar to the following one, I've experienced some situation where some variables worked wh...
Your code causes undefined behaviour, because your wMyStructure does not point to an object, so you may not use the accessor operator -> on it. An object only commences its life after its constructor has completed. Since you don't call any constructor, you do not have an object. (If your struct were a POD, i.e. just co...
7,085,759
7,089,477
Compile issues with OpenCV and Juce on Xcode4.1 in 32bit on Lion
I'm trying to compile my VST Plugin with Xcode4.1 in 32Bit. I'm using the Juce Framework and integrated OpenCV 2.2 in it. I installed OpenCV with homebrew and this command: sudo brew install opencv -build32 But when I'm compiling the project with Xcode4.1 in 32bit I will get this errors: Undefined symbols for architec...
I have solved the problem with the help of the wiki article section Using the OpenCV libraries in an Xcode OS X project. Just needed to add the dylib files to my project. :-)
7,086,303
7,086,328
Rotating from center rather than from left, middle
Im working on a system for skeletal animation and each bone's angle is based on its parent. I have to rotate that bone from the end of the parent joint for that angle to be accurate as illustrated in the first part of this illustration: What I need to do is the second part of the illustration. This is because my drawi...
Combine the rotation with a translation. Rotate the figure about the center, then move it to where it should be.
7,086,417
7,086,669
Conversion from C++ to Delphi (simple)
I have a function in C++ that I am attempting to replicate in delphi: typedef double ANNcoord; // coordinate data type typedef ANNcoord* ANNpoint; // a point typedef ANNpoint* ANNpointArray; // an array of points bool readPt(istream &in, ANNpoint p) // read point (false on EOF) { for (int i = 0;...
Try: type ANNcoord = Double; ANNpoint = ^ANNcoord; function readPt(inStr: TStream; p: ANNpoint): boolean; var Size: Integer; // number of bytes to read begin Size := SizeOf(ANNcoord) * dim; Result := inStr.Read(p^, Size) = Size; end; There is no need to read each ANNcoord separately. Note that istream is a...
7,086,502
7,086,676
Why does std::vector transfer its constness to the contained objects?
A const int * and an int *const are very different. Similarly with const std::auto_ptr<int> vs. std::auto_ptr<const int>. However, there appears to be no such distinction with const std::vector<int> vs. std::vector<const int> (actually I'm not sure the second is even allowed). Why is this? Sometimes I have a function w...
It's a design decision. If you have a const container, it usually stands to reason that you don't want anybody to modify the elements that it contains, which are an intrinsic part of it. That the container completely "owns" these elements "solidifies the bond", if you will. This is in contrast to the historic, more low...
7,086,585
7,088,597
Where are global variables of a DLL stored in memory?
Suppose you have a VB6 app which uses a C++ DLL. They share the same memory (you can use pointers from one in the other). The DLL is declared in the VB6 app with Public Declare Function ... Lib ... So how does this fit with the "Stack grows from one side of memory, heap from the other" philosophy? Where is the stack of...
VB6 uses thread local storage for module-level variables, not data segements. What this means is that public (global) variables in a module can have different values per different threads. Which is not what a C/C++ developer is used to.
7,086,788
7,086,848
c++ numerical analysis Accurate data structure?
Using double type I made Cubic Spline Interpolation Algorithm. That work was success as it seems, but there was a relative error around 6% when very small values calculated. Is double data type enough for accurate scientific numerical analysis?
Double has plenty of precision for most applications. Of course it is finite, but it's always possible to squander any amount of precision by using a bad algorithm. In fact, that should be your first suspect. Look hard at your code and see if you're doing something that lets rounding errors accumulate quicker than nece...
7,086,825
7,086,877
Can a python script decrypt a HASH that was created in a C++ program?
I have a competition that people can enter with a secret code they discover in an Android app. The method I have chosen to ensure only people who have purchased the app can enter the competition is to use shared secret encoded(encrypted?) with HMAC SHA256. So my secret will be encrypted in C in the Android app (using C...
When using a hash that way, normally you would pass the secret code (in plaintext) and the hash of both the secret code and the shared secret to your web site. The web site can then perform the same hash (as it knows the shared secret), and verify that the result is the same. 'Cracking' the hash on your server is a lot...
7,087,171
7,087,323
Linking static libraries with c++/cmake
I try to link libraries in my program using firebreath framework. So I add this code in projectDef.cmake. include_directories(/usr/include/giblib) include_directories(/usr/include/X11) add_library(giblib_ptm STATIC IMPORTED) set_property(TARGET giblib_ptm PROPERTY IMPORTED_LOCATION /usr/lib/libgiblib.a) add_library(...
I think you are misunderstanding the creation of a static library. A static library is a collection of object files, it does not have any init/deinit code to pull in additional libraries like a shared library or an executable can. If you create a libraryA that uses code from libraryB and libraryC when you build applic...
7,087,215
7,087,344
Iterating over keys/values of a std::map in C++
My question is a slight generalization of this one. For sake of discussion, I'll focus on iterating over the keys of a map. I would like to have a generic helper function, key_iterator, that takes a map iterator and returns a map key iterator. For example, the following code: #include "key_iterator.hpp" #include <algor...
Try this: template <typename Iter> struct KeyGetter : std::unary_function<typename Iter::value_type, typename Iter::value_type::first_type> { const typename Iter::value_type::first_type& operator() (const typename Iter::value_type& p) const { return p.first; } }; template<typename Iter>...
7,087,336
7,097,978
How to find out how much data was sent through a Boost ASIO TCP socket connection?
I have some shared pointers to boost::asio::io_service, boost::asio::ip::tcp::endpoint, boost::asio::ip::tcp::acceptor and boost::asio::ip::tcp::socket. I accept users connection and pass shared_ptr of the socket to some class of mine. It does its work. Now what I want is simple - count my traffic. I want to get info...
Assuming you use asynchronous methods, the completion handler given to async_read will indicate the number of bytes received. Similarly, the completion handler given to async_write will indicate the number of bytes written. It would be trivial to maintain a running counter as a member of a class where you bind methods ...
7,087,349
7,088,952
Compiler chosing prefix ++ when postfix is missing - who says?
When you define a prefix operator++ for your user defined type and you don't provide a postfix version, the compiler (in Visual C++ at least) will use the PREFIX version when your code calls the missing POSTFIX version. At least it will give you a warning. But, my question is: Why doesn't it just give you an error fo...
Actually, In this case the MSVC behaves much more intelligently than GCC. This is a MSVC compiler extension and the C++ standard explicitly allows for such an behavior. C++ Standard: Section 1.4/8: A conforming implementation may have extensions (including additional library functions), provided they do not alter the...
7,087,395
7,087,470
Improve my Shared Secret Algorithm/Methodology & suggest a Encryption Protocol
I am looking for protocol/algorithm that will allow me to use a shared secret between my App & a HTML page. The shared secret is designed to ensure only people who have the app can access the webpage. My Problem: I do not know what algorithm(my methodology to validate a valid access to the HTML page) & what encryption...
especially if the hash algorithm doesn't produce the same result for the same in put all the time. Then the hash is broken. Why wouldn't it? You want HMAC in the simple case. You are "signing" your request using the shared secret, and the signature is verified by the server. Note that the HMAC should include more dat...
7,087,396
7,087,414
C++ Debug Assertion Error
So, I've been playing around with c++ a bit and decided to write a program that involves opening and writing to a file in binary mode. I am not too familiar with the iostream functionality of c++ (I mostly do API based programming), but I read several technical guides on the subject and wrote some code. The code is mea...
You're passing MemBlock to SetMemBlock by value. The function therefore just sets the value of a local copy, which has no effect on the calling function; the value of MemBlock in the calling function thus remains garbage. Using it as a pointer will probably then lead to an assertion (if you're lucky) or an out-and-out ...
7,087,676
7,087,866
Tutorial on integrating CG shader into GL and D3D9?
I've found many tutorials on writing CG shaders but none that show how to integrate it into a D3D or GL scene. Is there a tutorial that would show how CG would integrate into these?
I'm using this on iOS/Android OpenGL ES 2.0, but this could work for you too: hlsl2glslfork. It's a library that you can compile/link right into you application, and it can translate your Cg/HLSL to GLSL right before you call glShaderSource.
7,087,958
7,088,188
File stat() vs access() to check permissions on a directory
I have successfully used both stat() & access() separately to determine if a user has either read or read/write access to a directory. My question is: - Is there a preferred method ? I see a lot of examples using stat, but for my purpose, access seems to be more lightweight and serves purpose. - Are there any issues ...
Either is equivalent for your needs. access() is a cleaner wrapper if you're not going to do anything with the stat structure that you populate. Just be mindful that you are creating a race when doing this. The permissions can change between calling stat()/access() and when you actually try and use the directory. Hell,...
7,088,005
7,088,768
Conversion of pointers and arrays from C++ to Delphi
I am trying to use the ANN (approximate nearest neighbor) library (the .dll) within my Delphi code. The library is written in C++, and although the data types are fairly simple I am having some trouble. I used h2pas to convert the C++ header file as far as I could get it. I ended up with the following data types (C++ o...
Your code calls the DLL function to allocate a array of 1000 2-element arrays of Double. Then you fill a stream with 1001 bytes. You're trying to populate 16000 bytes of storage with only 1001 bytes of data. Furthermore, the data you're putting in the stream doesn't form meaningful Double values anyway. Also, your vers...
7,088,196
7,299,183
PhysFS and Python embedding
I am writing a game engine and I'd like it to have Python scripting as well as support for mods using PhysFS. My game data is stored something like this: / native scripts sprites ... mods mymodname scripts What I want is for the mod scripts to be able to 'import' the native scripts as if they were in the same...
[I am the same person who asked the question.] The solution I used eventually was to modify Python's sys.path when my program starts. This does not pollute the game's data directories with symbolic links and is overall much cleaner.
7,088,292
7,088,323
C++ syntax: void CLASS functionName()?
I came across some standalone code without headers. I believe it to be straight C/C++, but am not sure. If so, what does the "CLASS" in the following mean? I know it's not a class declaration or definition. Is this a method of a class named "CLASS"? void CLASS functionName(){ // // // } I'm used to seeing <retur...
Although it's not common AFAIK, it could be that CLASS is a macro as below. Since its name is CLASS, I would say it's more likely that it's a macro for a class or namespace. 1. Class Name class A { void functionName(); }; #define CLASS A:: void CLASS functionName() {} 2. Namespace namespace A { void functionNa...
7,088,490
7,088,902
Boost::d_ary_heap_indirect DistanceMap template argument
I'm looking at using boost::d_ary_heap_indirect in my code, but I'm having trouble understanding one of the template arguments, DistanceMap. The comments (full source availible here) have this to say: // - DistanceMap must be a ReadablePropertyMap from Value to something // (typedef'ed as distance_type). I tried loo...
Yes, DistanceMap is a map from value to priority, aka key. D-ary heap is commonly used for Dijkstra's algorithm. In Dijkstra's algorithm, the priority is, especially, represented by the edge path cost(distance). I guess that's why its named like this. E.g., there is a method keys() to return this map. // return value-t...
7,088,586
7,088,682
how to run an C++ program in Android OS for Linux/Windows machine
How to install Android in our Computer(linux-Fedora ,Windows -XP) ,and I need to run c++ program (compiling & executing) .Please Provide the links & tell me the procedure .whether i need to install any C++ compiler like GCC,Sun compiler etc..i googled it but i dont find any crystal clear working methods guys direct me ...
Use android developer website to know how to run android in your pc. step by step installation of android sdk This site might be helpful for you for understanding how to run native code in android. android ndk
7,088,767
7,088,791
What is being declared here?
I came across this strange looking declaration in some code early this morning (before my cup of black coffee had had a chance to "kick in") ... IField const* f(0); That looks a bit unusual to me. Can anyone explain what the variable f is?
It's a pointer 'f' of type IField const (or const IField) that is initialized to 0. Same as for instance: const IField *f = 0;
7,089,035
7,090,074
At what moment is memory typically allocated for local variables in C++?
I'm debugging a rather weird stack overflow supposedly caused by allocating too large variables on stack and I'd like to clarify the following. Suppose I have the following function: void function() { char buffer[1 * 1024]; if( condition ) { char buffer[1 * 1024]; doSomething( buffer, sizeof( buff...
Your local (stack) variables are allocated in the same space as stack frames. When the function is called, the stack pointer is changed to "make room" for the stack frame. It's typically done in a single call. If you consume the stack with local variables, you'll encounter a stack overflow. ~512 kbytes is really too la...
7,089,284
7,089,649
Dynamic dispatching of template functions?
Is it possible to decide in run-time which template function to call? Something like: template<int I> struct A { static void foo() {/*...*/} }; void bar(int i) { A<i>::f(); // <-- ??? }
A typical 'trick' to bridge compile time and runtime when dealing with templates is visiting a variant type. That's what the Generic Image Library (available as Boost.GIL or standalone) does for instance. It typically takes the form of: typedef boost::variant<T, U, V> variant_type; variant_type variant = /* type is pic...
7,089,467
7,291,610
How to change image's alpha value without completely reloading every pixel each frame/ OPTIMIZATION
so I'm trying to bring an image to visibility in sfml 1.6 by changing it's alpha value every frame. unfortunately there isn't an overall alpha value for the image, so i have to go through each pixel, one by one and change it's alpha value. This is extremely slow however, so I wondering how I could possibly optimize my ...
Unless I'm misunderstanding your question, you should be able to use sf::Drawable::SetColor for this, giving white as the argument but with a differing alpha value. For instance, to set sprite's alpha to 50%, you could do the following: sprite.SetColor(sf::Color(255, 255, 255, 128));
7,089,479
7,089,549
Should one put output operations into a destructor?
I've got a class that collects and processes some data during the execution of the program, let's call it dataCollectionInterface. When the program terminates (or rather: a dataCollectionInterface object goes out of scope) some final processing and output of (some of) the collected data needs to be done. The question n...
You should not be throwing any exceptions from the destructor, So better to do it in a public function, rather than the destructor if your operations can throw exceptions and you need to do the exception handling for them. Though, If you can rather handle all your exceptions within the destrucotr itself without throwi...
7,089,494
7,089,564
Merge multiple sets elements in a single set
I would like to know if there is any std library or boost tool to easily merge the contents of multiple sets into a single one. In my case I have some sets of ints which I would like to merge.
You can do something like: std::set<int> s1; std::set<int> s2; // fill your sets s1.insert(s2.begin(), s2.end());
7,089,746
7,089,961
How to create a function pointer from a function with certain parameters fixed in C++
Suppose I want to call a function f that asks for a function pointer of type int (*foo)(int) The function is something like double f( int (*foo)(int)) I have a function that does this, but it takes another object. int bar(int, MyClass*) This object is created at runtime, say int main() // ... read some file / i...
Edit to account for the fact that f cannot be modified: Since you can't modify f, the only solution I can think of is using some sort of global variable together with a forwarding function: int bar(int i, MyClass * mc); namespace bar_parameters { MyClass * mc = 0; } int binded_bar(int i) { return bar(i, bar_...
7,089,978
7,090,181
C++ macro without spaces
I need a macro to expand to a c++ comment, is that possible? I've got this: #define SLASH(x,y) x y #define OUT SLASH(/,/) int main(int argc, char *argv[]) { OUT << "text"; return 0; } And need to expand to this: { // << "text"; return 0; } I've also tried this: #define SLASH(x) /x #define OUT SLASH(/) But t...
As others mentioned there is no guaranteed way to define the kind of macro you are looking for. Other ways to achieve results that are similar to what you seem to be trying to achieve are wrapping your output statement in a conditional block or define a custom output stream that just discarded all output. The two appro...
7,089,989
7,090,547
cuda algorithm structure
I would like to understand the general way of doing the following on a GPU using CUDA. I have an algorithm that might look something like this: void DoStuff(int[,] inputMatrix, int[,] outputMatrix) { forloop { forloop { if (something) { DoStuffA(inputMatrix,a,b,c,outputMatrix) ...
It depends on how the data inter relates to each other in the for loops, but roughly I would Pack all input matrices into a block of memory Upload input matrices Do for loops on CPU, calling kernels for DoStuffA and DoStuffB Download output matrices in one block This way, the biggest problem is overhead for calling e...
7,090,367
7,125,627
assigning value from a vector (of shared pointer) to a shared pointer cause segmentation fault c++
In my code, I have a vector <vector <vector <vector <std::tr1::shared_ptr<foo> > > > > named foosBoxes. The nested vector has a role of simulating a physical boxes position. I also have a while loop which cause a segmentation fault: vector<std::tr1::shared_ptr<foo> >::iterator fooit = foosBoxes[x][y][z].begin(); //x,...
I have came to the conclusion that the problem was with the use vector is wrong since I update it through the code. I don't know how the memory management in c++ works but I believe that some sort of overlapping between two vector occurred. I have switched to set and everything works now
7,090,611
11,741,317
What would make C++ preprocessor macros an accepted development tool?
Apparently the preprocessor macros in C++ are justifiably feared and shunned by the C++ community. However, there are several cases where C++ macros are beneficial. Seeing as preprocessor macros can be extremely useful and can reduce repetitive code in a very straightforward manner -- -- leaves me with the question, ...
Most preprocessor abuse come from misunderstanding, to quote Paul Mensonides(the author of the Boost.Preprocessor library): Virtually all issues related to the misuse of the preprocessor stems from attempting to make object-like macros look like constant variables and function-like macro invocations look like un...
7,090,896
7,094,543
Why would a C++ program allocate more memory for local variables than it would need in the worst case?
Inspired by this question. Apparently in the following code: #include <Windows.h> int _tmain(int argc, _TCHAR* argv[]) { if( GetTickCount() > 1 ) { char buffer[500 * 1024]; SecureZeroMemory( buffer, sizeof( buffer ) ); } else { char buffer[700 * 1024]; SecureZeroMemory( buffer, ...
The following code when compiled using GCC 4.5.1 on ideone places the two arrays at the same address: #include <iostream> int main() { int x; std::cin >> x; if (x % 2 == 0) { char buffer[500 * 1024]; std::cout << static_cast<void*>(buffer) << std::endl; } if (x % 3 == 0) { char buffer[700 ...
7,090,930
7,119,404
JNI FindClass fails with imports
I'm trying to call my java class from c++ (ms vc 2008) with JNI, but the problem is that FindClass works only when there are not imported packages in my java class. If I add any package (for example java.lang.String or java.io.File) the FindClass fails and returns no value. Why? C++ CODE: //////////////////////////////...
I have found the problem. If I select in Eclipse\Jar Export\ the option "Export generated class files and resources" AND I put some import in my java class, the generated JAR file will not include any .class file. Instead the option "Export all output folders for checked projects" works anytime. I don't know why, but I...
7,090,998
9,602,511
Portable UNUSED parameter macro used on function signature for C and C++
I'm interested in creating a macro for eliminating the unused variable warning. This question describes a way to suppress the unused parameter warning by writing a macro inside the function code: Universally compiler independent way of implementing an UNUSED macro in C/C++ But I'm interested in a macro that can be used...
After testing and following the comments, the original version mentioned in the question turned out to be good enough. Using: #define UNUSED(x) __pragma(warning(suppress:4100)) x (mentioned in comments), might be necessary for compiling C on MSVC, but that's such a weird combination, that I didn't include it in the end...
7,091,385
7,094,613
How to organise my files using CMake?
I am having a bit of a problem with CMake regarding the organisation of my code within a solution. I have for an habit to organise my namespace by creating a directory for each. For example if I create something like this : namespace test { namespace blabla { ... } } I would create a directory test and inside of it a...
Try using the source_group command. After the call to add_executable add source_group statements to structure your project as you wish, e.g.: source_group("test\\blabla" FILES file1.cpp file2.cpp)
7,091,548
7,091,746
Class interface design woes
I'm having doubts about how to best construct the interface of a new class. There will be two other classes communicating with the new class, Platform and Sensor. The new class, Pathfinder, will recieve sensor data from Sensor and take any new data in account when calculating paths. Platform is moving along the path cr...
You could use the design pattern "Observer". Then the Platform object could subscribe to the Pathfinders events "Started recalculation" (immediately stop moving or go back or ...) and "Calculation finished". When there is a new path at the Pathfinder object, the Platform object can ask for the whole data at once.
7,091,712
7,091,758
Problem in C++ class with static variables and functions
Can someone tell me what is problem in the following class, g++ is giving errors on ubuntu: class FibonacciGenerator { private: static int num1, num2, counting; public: static void Reset() { num1 = 0; num2 = 1; counting = 1; } static int GetCou...
The statement static int num1, num2, counting; in a class definition does not define those variables, it only declares them. If they are used they must also be defined. A complete example of this is as follows: //Begin FibonacciGenerator.hpp #ifndef FIBONACCI_GENERATOR_HPP #define FIBONACCI_GENERATOR_HPP class Fibonacc...
7,091,748
7,092,082
Add button click handler in Qt project, Visual Studio
I have Qt SDK and Visual Studio Qt Add-In working in VS2008. I created Qt UI project with main window class MainWindow. Double-click on mainwindow.ui opens Qt Designer. Then I added push button to the window, and called it pushButton. In Signals-Slots mode I managed to connect button's clicked signal with MainWindow Bu...
If you use signal/slot editor, you have to add these codes manually. Old Qt Add-In was automatically add these if you double click on a button from designer. Now Qt Designer is a seperate application. Double clicking is not possible. Also you can use automatic connections. With automatic connections you dont need to co...
7,091,784
7,092,259
Direct Initialization vs Copy Initialization for Primitives
When initializing primitive types like int or pointers one can use either copy-initialization or direct-initialization. int a = 10; int b(10); Although the latter way is preffered for objects with constructors, I don't see people using it for primitives. I understand that it is kind of "more natural" (especially for n...
Some people do this to be consistent. Inside a template, the code could be for (T i(0); i < 5; ++i) { cout << i << endl; } and writing it that way everywhere would make the coding style consistent.
7,091,830
7,092,283
Qt destructor call for closed widget
There is application that handles text commands. I have a Qt widget that is closed with some close * command. Qt::WA_DeleteOnClose attribute is set for that widget, it receives closeEvent, but destructor for that object is called later (I guess on idle). If I have two commands close *; get something; the program crashe...
Setting Qt::WA_DeleteOnClose means qt can delete anytime after you call close() because qt uses deleteLater() internally. You can ensure the deletion using QObject::destroyed() signal.
7,091,903
7,106,284
Problem with Multigradient brush implementation from scatch in C++ and GDI
I am trying to implement a gradient brush from scratch in C++ with GDI. I don't want to use GDI+ or any other graphics framework. I want the gradient to be of any direction (arbitrary angle). My algorithm in pseudocode: For each pixel in x dirrection For each pixel in the y direction current posi...
Ok guys fixed it. Apparently the problem was that when I was rotating the gradient fill (not the rectangle) I wasn't calculating the scaling factor correctly. The distance over which the gradient is scaled changes according to the gradient direction. What must be done is to find where the edge points of the rect end up...
7,092,069
7,092,262
WM_CLOSE in modal message loop
I am using a special message loop for a custom dialog box. When the dialog box is open and the window is closed, I would like to reach the second if below, if(msg.message == WM_CLOSE). for(;;) { if(PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE)) { if(msg.message == WM_CLOSE) { GetMessage(&...
It seems that WM_CLOSE is sent, and the other message is posted. GetMessage and PeekMessage only operate on posted messages (those posted with PostMessage). If a message is not posted but sent via SendMessage, it's handled immediately inside PeekMessage or GetMessage, so you can not get MSG struct for it.