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,311,544 | 7,311,653 | Using Preprocessors to change language Syntax | I read that Objective-C was made by using preprocessor directives to add features of Smalltalk to C, which got me a little curious so I started tinkering with preprocessors in C++, just because I was bored and came up with this:
#include <iostream>
#include <string>
#define Constant const
#define Integer int
#define Re... | A language like Objective C can be implemented using a preprocessor, but not the C preprocessor, as the C preprocessor language is fairly limited, if it even is turing complete (it may not be), it's at best a really nasty turing tarpit. A more powerful preprocessor will allow more significant alterations to syntax.
A p... |
7,311,602 | 7,555,530 | JNI lib crash, with a change in a .c file which is not included in the Makefile | We are facing an unusual problem, our JNI lib crashes at load time.
we use CentOS 5.4/G++ and VS2005 for development.
scenario:
we are currently working on an enhancement in our product and wanted to pass the new information back to the Java server code using JNI.
our C/C++ code works fine and we have tested it by runn... | finally, we are able to solve this issue.
We were seeing this issue because the Makefile we used to build the JNI lib had a lot of .o files which were not needed by the build.
one of the file happened to be the one, we were modifying, but other dependent files were not included in the Makefile and this was causing the ... |
7,311,641 | 7,311,658 | How does a vector<T> get resolved as a function parameter for a templated function? | I have a helper function that creates an Array_Ref obj. The function has a parameter, vector<t> - that the compiler is complaining about. I'm using VS2010.
I put the function in a .h by itself.
I put the function in Array_Ref.h
I put it in a .cpp file.
I put typename in front of vector<T>
I put typedef typename in fro... | It's std::vector, not vector. Also, you don't appear to have defined Array_Ref anywhere.
|
7,311,848 | 7,311,873 | Removing elements from dynamic arrays without changing the index order | I've been trying to erase an element from an array without changing the index order, for instance:
class MyObject
{
int id;
public:
MyObject() { }
void setId( int i ) { id = i; }
void showId() { std::cout << "ID: "<< id << "\n"; }
};
MyObject *myArray;
int main ( )
{
myArray = new... | You are calling memset to write a bunch of zeros over the top of an object instance. Do not do this! You may get away with it if your class is a true POD class. You might end up just setting the ID to 0. But maybe there is more to your class that you aren't showing. In anycase, even if it isn't POD, don't use memset li... |
7,312,502 | 7,312,665 | Move bottom quarter of a vector to the top efficiently? | Given a vector with 100 elements, I want to move elements 75 to 100 to the front so that 75 is array[0], 76 is array[1] and 1 is array[25].
Thanks
| Your description sounds like you need std::rotate:
std::rotate(v.begin(), v.begin() + 75, v.end());
|
7,312,554 | 7,312,735 | error: assignment of data-member ‘RootBoxT<CORE::DoubleWrapper>::innerBox_’ in read-only structure | I encountered an error as the topic says: assignment of data-member ‘RootBoxT<CORE::DoubleWrapper>::innerBox_’ in read-only structure. I "might" know why does this happen, but I need to learn more about the rules.
I made all instances for RootBoxT as const, and the member variable *innerBox_ of class RootBoxT is also ... | If you have something like this:
struct S
{
int * i;
};
and a const S object (s), the pointer s.i is const but not the int it points to (*s.i). This means you can write:
*s.i = 4;
delete s.i;
but not:
s.i = new int (5); // illegal
int * j = 0;
s.i = j; // illegal
because that would modify the pointe... |
7,312,700 | 7,312,733 | Properly seeding a RNG for a card game | I'm working on a card game and I need the shuffle algorithm to do a very good job and to be different every time the game runs and to not have predictable card sequences.
I'm using the Mersenne twister algorithm but it still needs a seed, so really, although it produces great numbers, right now there are only 1000 poss... | My standard seeding technique:
If /dev/urandom exists, read a seed from there.
If you're in Windows, use CryptGenRandom().
If all else fails, use time().
(Not sure where your Mersenne twister comes from, but there new standard library has one in <random> which integrates very elegantly.)
I'm happy to hear suggestions... |
7,312,743 | 7,312,775 | Unhandled exception check in C++ | Is there any way in C++ to get a compile-time error or warning if an exception is unhandled? For example, consider this Java code snippet:
public void f()
{
g(); // <-- Java compiler reports "Unhandled exception" error here.
}
public void g() throws Exception
{
}
Can g++ or MSVC do something similar? Or is there... | Simply, no. C++ exception specifications have a different meaning to Java's exception specifications and they are now deprecated so you should consider avoiding them if possible.
In C++, the checks requested by exception specification are enforced only at runtime. In C++, if a function violates its exception specificat... |
7,312,745 | 7,312,757 | static_cast for user defined types | Is it possible and why one would want to do it?
class Foo;
class Bar;
......
Foo foo;
Bar bar = static_cast<Bar>(foo);
Normally static_cast is used with numeric types and pointers, but can it work with user defined data types, a.k.a classes?
| Bar bar = static_cast<Bar>(foo);
This cast will fail. Foo and Bar are incompatible types, unless atleast one of the following is true:
Foo is derived from Bar, Or
Bar has a constructor that takes Foo, Or
Foo has a user-defined conversion to Bar.
The bigger question here is not whether it will cast successfully or n... |
7,312,908 | 7,312,955 | Windows Programming: WNDCLASS structure: hIcon member Problem | I've Created a custom .ico with VS2010 for a game I'm making with DirectX
When I set the .ico file as hIcon member of my wndClass, it will show in the taskbar, but not in the title bar.
I've read the other threads about this, I've searched google, msdn: no luck... I've tried just about anything I could come up with, it... | You have to specify an instance handle in your call to LoadIcon so it knows which module's resources to use.
The standard icons require a NULL instance, that's why they work for you.
|
7,313,160 | 7,519,009 | Union iterator for maps? | [Preface: The associative C++ containers like std::map are a bit like micro-databases with just one key column. Boost's bimap elevates this to a two-column table with lookup in both columns, but that that's as far as the analogy goes -- there's no "polymap" that generalizes the idea.]
In any event, I want to keep think... | As I announced, I have got something pretty cool.
I'm posting it now, because I wouldn't be sure whether I'd be back in time tonight to post it. I will be spending a few words in explanation. (in this post)
PS. The includes will be trimmed down (to about 20%); I will probably do some more general work on the code too.... |
7,313,438 | 7,313,458 | Windows service lifetime and duty | I need a management application running with no-gui, doing some periodic jobs and connectable anytime by another console or desktop application.
On Linux, it would be a daemon. Is Windows service project equivalent on Windows?
| If you want a program to run periodically, you should consider using Task Scheduler (the equivalent of cron) - setting this up will be much easier than using a Windows Service. However, if you need to be able to connect to it 24/7, you are correct that a Windows Service is equivalent.
|
7,313,544 | 7,313,649 | A std::string gets a totally unexpected value | My class has a member std::string received;, initialized at an empty string in its constructor, along with a function printReceived that prints the string to cout.
In main(), an instance of the above class is created, and printReceived is called.
Instead of getting an empty string, I get totally unexpected values (but ... | operator+= has lower precedence than operator+. So in println, you're doing this:
received+=(s+'\n');
Which is like
received+=(s+10);
Which is incrementing the pointer s by 10 bytes and then appending the string pointed to by the resulting char* to received, and the string literal Recieved: is happening to be stored ... |
7,313,622 | 7,313,632 | Calling method of child class on a vector of parent class | #include <iostream>
#include <vector>
using namespace std;
class Parent {
public:
Parent();
void method();
};
class Child: public Parent {
public:
Child();
void method();
};
int main() {
vector<Parent> v;
v.push_back(Parent());
v.push_back(Child());
v[0].method();
v[1].method();
... | You are encountering the slicing problem.
vector<Parent>.push_back() copies its argument, so it invokes Parent::Parent(const Parent &) (i.e. the copy constructor)*.
This is really no different to:
Parent x[10];
x[0] = Parent();
x[1] = Child();
* Or it might be Parent::operator=(const Parent &), i.e. copy-assignment. ... |
7,313,642 | 7,324,700 | Using child class as a template parameter of a base class and as a nested name specifier | I'm using my class as a template parameter of one of its parent class, and that parent class uses it in a template argument (though sizeof()).
And the compiler gives me:
error : incomplete type 'Invoker::workerClass {aka MyClass}' used in nested name specifier
Yet the class is well defined in the file. I guess this... | The solution was, as ildjarn pointed out, to add another level of indirection.
That is done by changing the test function to accept types:
template <typename X, class U = void>
struct test {
typedef U type;
};
And then pass the child class as a template parameter, instead of specifying it from the get go:
temp... |
7,313,690 | 7,313,787 | Most effective method of executing functions an in unknown order | Let's say I have a large, between 50 and 200, pool of individual functions whose job it is to operate on a single object and modify it. The pool of functions is selectively put into a single array and arranged in an arbitrary order.
The functions themselves take no arguments outside of the values present within the ob... | If the behaviour functions have no state and only take one Object argument, then I'd go with a container of function objects:
#include <functional>
#include <vector>
typedef std::function<void(Object &)> BehaveFun;
typedef std::vector<BehaveFun> BehaviourCollection;
class Object {
BehaviourCollection b;
void beh... |
7,313,919 | 7,314,430 | C++11 alternative to localtime_r | C++ defines time formatting functions in terms of strftime, which requires a struct tm "broken-down time" record. However, the C and C++03 languages provide no thread-safe way to obtain such a record; there is just one master struct tm for the whole program.
In C++03, this was more or less OK, because the language didn... | You're not missing anything.
The next C standard (due out probably this year) does have defined in Annex K:
struct tm *localtime_s(const time_t * restrict timer,
struct tm * restrict result);
And this new function is thread safe! But don't get too happy. There's two major problems:
localtime_... |
7,313,989 | 7,314,008 | Forking child process and C++ objects | I have several questions. Any input is appreciated. Thank you.
Do C++ classes survive forking?
If so, how it is implemented?
What happens to pointers? Entire free store/heap is replicated and all virtual addresses are preserved?
What happens to file streams?
| Here's my understanding:
Do C++ classes survive forking?
yes.
If so, how it is implemented?
All of memory is copied so you have no trouble there.
What happens to pointers? Entire free store/heap is replicated and all virtual addresses are preserved?
yes.
What happens to file streams?
Both processes retain a cop... |
7,314,192 | 7,314,283 | what is the best, efficient approach to rank the candidates | There are N candidates who sign up answer a series of multiple-choice questions. Design a efficient method to evaluate the answer and rank the candidates.
vector <string> Evaluate (const string& answer, const vector<string>& param)
{
// answer - will have the answer for multiple choice question.
// like X X X X... | You can compute the score for a single candidate without tokenizing, if you assume a single space between answers. First, search for the first space to skip then name, then pass the remaining string to the following function
int compute_score(const string& answer_key, const char answer[])
{
int score = 0;
for (uns... |
7,314,394 | 7,316,598 | Size of "vector of objects" Versus "vector of Object pointers" | I'm trying to understand how much memory is taken up by using a vector of objects versus vector of pointers. I wrote a small test code:
class Test {
public:
Test()
{ v.resize(2000); }
private:
std::vector<int> v;
};
int main()
{
std::vector<Test> OCtr;
std::vector<Test*> PCtr;
Octr.resize(10);
... | sizeof is a compile-time operator. That is, sizeof(X) will be replaced during compilation with a constant number. This means that the sizeof an empty vector<T> is always the same as the sizeof a vector<T> with thousands of elements inside of it. Remember, sizeof does not do anything during runtime, so the result cannot... |
7,314,891 | 7,315,178 | how to get C++0x / C++11 style range-based for loops to work with clang? | I've been taking advantage of range-based for loops in C++0x/11 using gcc w/ -std=c++0x like so:
for (int i : container) ...
I recently tried clang (clang+llvm-2.9-x86_64-apple-darwin10), but out-of-the-box these statements were compilation errors. According to http://clang.llvm.org/cxx_status.html it's supported. I t... | The secret here is that LLVM 2.9 doesn't support range-based for loops. That document corresponds to LLVM/Clang mainline. To get range-based for loops, please check out LLVM/Clang from mainline SVN: http://clang.llvm.org/get_started.html
libc++ is useful for C++'0x ('11!) library support, but you also have to set it ... |
7,315,126 | 7,315,189 | choosing between android and iOS for a programming novice | I've been wanting to get into mobile/tablet app development but I'm not sure whether to go with iOS or Android. Here are a few specific questions I had:
What would you recommend for someone who has a background in python and C++?
Is developing for the honeycomb os for tablets pretty much the same as android develop... |
What would you recommend for someone who has a background in python
and C++?
Android uses Java as the main programming language, iOS uses Objective-C.
IMHO Java is easier to learn and more consistent compared to Obj-C.
Is developing for the honeycomb os for tablets pretty much the same as
android development?
... |
7,315,144 | 7,315,209 | UTF-8 on old MFC project converted to newer MFC | So project is Multi-byte by design. Recode full project to Unicode is to big work :(
So how can I use UTF-8 on my dialogs ? I've got this :
| You can try to use MultiByteToWideChar with UTF8 code page. But, since I'm not sure how you pass ??? texts to the dialog, this might not be a solution. Similarly, if you try to pass UTF8 string to where MultiByte expected, you can try WideCharToMultiByte with UTF8 code page.
|
7,315,337 | 7,315,374 | Get quadrant value after reflecting points across x axis | I have a number of points on a 2D graph, and I am concerned with they quadrant they lie in than the actual coordinates itself. I have a function ReflectX() which performs "Reflecting along X-axis" on a subset and returns the updated quadrant in which the points now lie.
So, points originally in quadrant 1 will now lie ... | You can get a much simpler answer by just looking at the table of all possible inputs and outputs:
Initial quadrant Reflected quadrant
1 4
2 3
3 2
4 1
So, just do this:
q[i] = 5 - q[i];
|
7,315,499 | 7,315,540 | Debug Assertion Fault on MFC CLR project | On closing mfc clr application, I've got message :
What it means ? How can I fix it ?
| This is almost certainly a memory corruption issue somewhere in your program code.
For example, you have copied a hundred bytes into a twenty-byte array, overwriting some vital information in an unrelated variable or structure.
The fact that the assertion is coming from the Microsoft run time libraries (which have been... |
7,315,671 | 7,315,735 | Byte padding issue on cross arch | I have noticed that sizzeof() on my program structure is different on x86 and x64 platform. This is becaue of bytes padding. Due to one requirement (where my application talks between cross arch m/c), i need to make sure that target should get the same size of structure what sender had send through a nammedpipe (in my ... | If you type #pragma pack(1) before your structure it should disable padding. This works on both visual studio and gcc. You probably also want to use #pragma pack(push) and #pragma pack(pop) to save and restore the previous padding rules.
For example:
#pragma pack(push)
#pragma pack(1)
struct
{
...
};
#pragma(pop)
|
7,315,679 | 7,316,139 | How do I avoid copy-pasting code blocks when only minor things need changes? | This is difficult for me to put into words, but say I have some function:
a = a + b;
printf("HI THERE");
b = a + c;
(pretend this is 30 lines instead of 3 lines). Now say I want to do the exact same thing again later on, except instead of printing "HI THERE" I print "HO THERE". What I currently do is copy paste all ... | I'm late to the party so I'll only be addressing your updated code.
First off, I see you printing error messages to stdout (via printf) and then calling exit. Why? You should print error (and perhaps debugging) messages to stderr (with fprintf(stderr, ...) or with perror, though perror is better if a library routine fa... |
7,315,752 | 7,315,807 | 4 signed bytes packed into a 32-bit unsigned | // Declaration of data type where 4 bytes are packed into an unsigned.
int xbyte(packed_t word, int bytenum);
int main()
{
int bytenum = 0;
typedef unsigned packed_t;
packed_t word;
}
// Extract byte from word, return as signed integer.
int xbyte(packed_t word, int bytenum)
{
// Failed attempt at x... | You already have a typedef line. Make it the first line of this piece of code, and you are done. The basic thing is that the typedefed name must be visible everywhere you use it.
|
7,315,774 | 7,315,787 | Google Interview Question | This was one of Google Interview questions.
What is the possible problem if Hash Table grows more than 30 gb
(ignore problems like bad hash function )
I didn't know it. What could be satisfactory answer ?
Thanks
| Some problems :
Hash Collision might be one of the major problem possible.
It will be also inefficient to make frequent disk reads when data store in disk as hash table.
|
7,316,003 | 7,316,185 | Mutable priority queue allowing key increase | When implementing a graph search algorithm, I needed a priority queue which allowed for priority changes. Until now, I've been using the (detail namespaced, so undocumented) boost d_ary_heap_indirect, but was just told it is undefined to have priorities increase (which I see now is also mentioned in the concept documen... | The Boost.MultiIndex library features container that have operations to update the state of the object and will accordingly update the indexes.
In your case, the modify member function seems to fit. From the documentation:
struct change_name
{
change_name(const std::string& new_name):new_name(new_name){}
void oper... |
7,316,161 | 7,316,366 | what does list/map return when insert failed? | when insert new element to list/map, it returns the iterator pointed to the newly added element.
But if insert failed, what does list/map return? I have read the references, when failed, list/map will not throw a exception.
| If insert cannot allocate the memory, bad_alloc is thrown. In all other cases insert works perfectly. link
Update: It also needs to copy the inserted object which can throw any exception.
|
7,316,173 | 7,316,196 | Do comments affect compile time? | I'm an Android developer and the following question came to my mind: When I put a big comment in order to compiling process, is that while we put our useful comment in code , can compiler take some time at comment portion?
If no, then is it not get any effect since how long our comment?
|
can compiler take some time at comment portion?
Apart from the IO overhead of traversing the bytes corresponding to the comment (which should be negligible as long as it's not a several megabyte long comment), it will make no difference what so ever. Most compilers don't even include the comments in the AST, which me... |
7,316,396 | 7,320,501 | Qt Whats This using a link/anchor | How can I put an anchor <a> into a whatsThis for a widget an intercept it being clicked?
I know about linkActivated in a QLabel, or linkClicked in a QTextBrowser, but I don't know how I can do the same thing with a Whats This text.
To be clear, I want to know if this is possible without interception help events and man... | If I understand your question, it's that you want to know if there is a SIGNAL() for this. There does not appear to be. Seems you have to watch for the QWhatsThisClickedEvent by deriving your own Widget class or with some kind of global filter:
http://qtcentre.org/archive/index.php/t-7394.html
FYI, the actual point whe... |
7,316,433 | 7,316,497 | difference between Console (/SUBSYSTEM:CONSOLE) and Windows (/SUBSYSTEM:WINDOWS) | can somebody please explain difference between those two declarations in the properties of the linker in visual studio 2008( please as simple as possible, I'm new in the world of C++) thanks in advace
edit: if possible can you give me please two small programs to show an effect
| /SUBSYSTEM:CONSOLE) is for console based applications. You should define main function in code.
/SUBSYSTEM:WINDOWS) is for GUI applications. You should define WinMain function.
|
7,316,513 | 7,316,556 | C++ friend function declaration between two seperate files | I've been instructed to create two Classes: Customer and Barber,
Barber should have a function : cutHair() that can change the value of private member hairLength in Customer.
Customer.h
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include "barber.h"
#include <iostream>
#include <string>
using namespace std;
class Custome... | In Barber.h you are forward declaring Customer (class Customer;) AND including #include Customer.h". Try removing the include. Of course you will have to add the include in your Barber.cpp
|
7,316,594 | 7,316,787 | php file: use dlopen and dlsym. how | I have myCode.so file created my linking a .c and .h file. I would like to call this .c file using the myCode.so and dlopen and dlsym . How to do that from php? I need some help! thx.
2.
Is there a way to import inside php (config.m4, php_example.h and php_example.c and example.php) a test.cpp code that uses the myCod... | If you compiled a PHP extension with the PHP build system (phpize && ./configure && make), you only need to tell PHP to load the extension, and it will take care of dlopen etc:
extension=myCode.so
(myCode.so as to be in extension_dir)
For functions to be callable from PHP code, you have to use the PHP_FUNCTION macro (... |
7,316,633 | 7,316,845 | Boost Thread - How to acknowledge interrupt | I have blocking task which will be performed by find_the_question() function. However, I do not want thread executing this function take more than 10 seconds. So in case it takes more than 10 seconds, I want to close that thread with cleaning all the resources.
I tried to write a code for that, but somehow I am not abl... | For using boost::thread::interrupt(), you have to use boost::thread::sleep() for it to work.
A running thread can be interrupted by invoking the interrupt() member
function of the corresponding boost::thread object. When the
interrupted thread next executes one of the specified interruption
points (or if it is ... |
7,317,019 | 7,317,234 | template to access different members of objects passed as arguments | I have a function to compute gradient of different variable defined on set of neighbor points. The algorithm is always the same, but depending on what is computed, different member data of the neighbors are accessed, e.g. when computing gradient of velocity, use Node::velocity, when computing gradient of stress, use No... | Pointer to member is what you need. The type is written as T S::* T is the type of the data member, S is your struct or class. Here is a small example:
#include <iostream>
struct Foo
{
int a;
double b;
Foo(int a, double b)
: a(a), b(b)
{ }
};
template<typename T, T Foo::* mem>
void print(const Foo& foo)... |
7,317,193 | 7,317,221 | How can we create an instance in C++ by a string type name? | Suppose we only have a string
string typename = "int"
How can we get an instance by this typename.
| In C++ you cannot have a type just from a string (or character array). Type must be declared at compile time.
[P.S. typename is a keyword in C++, so it cannot be used as variable.]
|
7,317,281 | 7,317,367 | How can i read a REG_BINARY values associated value from registry? | In the registry there is one ( or more ) key depending how many monitors you have HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\DISPLAY\DEL404C\{Some Unique ID}\Device Parameters\EDID which is a REG_BINARY key. In my case this is :
00 FF FF FF FF FF FF 00 10 AC 4C 40 53 43 34 42 34 14 01 03 0A 2F 1E 78 EE EE 95 A3 5... | DWORD GetLocalMachineProfileBuffer(BYTE* pBuffer, DWORD nMaxLength )
{
CString szSubKey = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\DISPLAY\DEL404C{Some Unique ID}\Device Parameters\EDID";
DWORD rc;
DWORD dwType;
HKEY hOpenedKey;
if( ERROR_SUCCESS == Reg... |
7,317,442 | 7,318,005 | Windows application crash .dmp file analysis in visual studio | To get the dump file (for crashes) I am using the userModeProcessorDumper.exe. Now the question is how to read this file (to see the stack information). Regarding this I have couple of questions
Yes I know I can use WinDbg (related tools) to analyze the .dmp file. My question is - Can this be analyzed in Visual Stud... | From what I remembered, VS6 cannot be used to debug dumps. It's been a while since I last used it, and trying to verify me memory I came across a workaround that might allow you to debug those dumps after all: Visual C++ 6, and post-mortem (crash dump) debugging.
I don't have VC6 at hand, and have no idea if this reall... |
7,317,488 | 9,724,360 | Export array content during debug using Visual Studio | I'm currently porting some huge arithmetics from MATLAB to C++ including vast amount of data. I would like to step over C++ code in VS and compare contents of the key arrays with ones from MATLAB code being debugged simultaneously. Since there are many steps, it's very ugly to use some real C++ code for exporting value... | After all, I was able to use >d command along with slight "packing" of my data to fit more in one string and performed several dumps. Since it was the one-moment task, solution is appropriate.
|
7,317,523 | 7,317,638 | What should I use instead of windows.h in Linux? | I am trying to port a Windows program to Linux. I have never programmed in Linux and have very little idea what I am doing. I have managed to eliminate a lot of the errors I got in the G++ compiler on Linux and have traced most of the remaining ones to non existent variable types.
I took out the windows.h file but I d... | The missing typedefs (HANDLE etc.) aren’t your problem. Your problem is that Linux and Windows have completely different APIs, you cannot simply hope to port one to the other by replacing a few type definitions.
The complete platform-dependent portion of your code has to be replaced. Your first step is therefore to lea... |
7,317,530 | 7,317,590 | Other way to prohibit a certain C++ class construction except than declaring the constructor private? | Say I have a class with some const reference member variable and I would like to forbid a certain type of construction. So I would declare the according constructor private. Of course, a constructor must initialise all const reference member variables of the class. Doing so, however, results in odd looking code:
clas... | Simply don't define this:
B():host(A()) {} // This is ugly and not needed !!
That is, the following should do what you want to do:
class B {
B(const A& a): host(a) {}
private:
//B():host(A()) {} // This is ugly and not needed !!
const A& host;
};
The idea is if you've defined a constructor that takes parame... |
7,317,819 | 7,317,878 | Releasing attributes' memory of singleton class | Considering the following Singleton class, I am not releasing memory in the destructor. But the instance of this class will remain the life-time of the program as most of the single-ton class do. Is it really matter to release the attribute's memory other than best practices perception?
class Singleton
{
private:
S... | It does matter for debugging. If you run a tool for detecting memory leaks, the leaks caused by this singleton will pollute the output, making it harder to detect real memory leaks.
|
7,317,869 | 7,348,049 | How to build LibXtract as DLL on Windows | Nowdays I'm just trying to use some audio libraries, and the LibXtract is one of them. With the help of gcc, I built LibXtract as static library and everything went ok :)
But when I tried to use the lib in MSVC, I met a problem : since the lib static format is not compatible between gcc and MSVC, I just tried to compi... | I've searched the LibXtract codes and found that there seems no dll-output codes in it, so I think that LibXtract may be just can be compiled into static format now, otherwise you have to modify the library codes...(not so sure)
Now I just copied the original codes and config.h which is generated by sh ./configure oper... |
7,317,952 | 7,320,712 | Regular expression to get HTML table contents | I've stumbled on a bit of challenge here: how to get the contents of a table in HTML with the help of a regular expression. Let's say this is our table:
<table someprop=2 id="the_table" otherprop="val">
<tr>
<td>First row, first cell</td>
<td>Second cell</td>
</tr>
<tr>
<td>Second ro... | There really isn’t a possible regex solution that works for an arbitrary number of table data and puts each cell into a separate back reference. That’s because with backreferences, you need to have a distinct open paren for each backref you want to create, and you don’t know how many cells you have.
There’s nothing wr... |
7,318,015 | 7,318,255 | Using keying material generated by OpenSSL handshake to encrypt/decrypt data locally | I'm currently working on a project which requires OpenSSL encryption.
Due to design considerations (which are unfeasible to work around) the encryption process has to be along these lines:
1) Perform SSL handshake
2) Obtain keying material generated from the handshake
3) Use said keying material to encrypt/decrypt the ... | I think BIO_s_mem() is the way to go for you.
http://www.openssl.org/docs/crypto/BIO_s_mem.html
http://books.google.com/books?id=IIqwAy4qEl0C&lpg=PT105&ots=ma051L5CVu&hl=en&pg=PT107#v=onepage&q&f=false
|
7,318,057 | 7,318,108 | Try for x seconds, then leave? | Is it possible to write in C++ try,catch statement with timer in that way that if function is not able to be executed (it's stuck) program just continues?
| Yes, you could do this with, for example, Boost.Thread.
Look especially at the timed_join function.
|
7,318,143 | 7,318,371 | Converting between jdoubleArray and vector<double> in a Java Native (JNI) method in C++ | I have a C++ dll that contains methods that I need to use in a Java program. I've been through all the Sun documentation on JNI, and numerous tutorials I found on the web, and I can't seem to find the problem with my code. In fact, a fair portion of the code is cut and pasted from various tutorials and the Sun website.... | According to the documentation, GetDoubleArrayElements may return a
pointer to a copy, rather than a pointer to the actual data; this is why
you need to call ReleaseDoubleArrayElements, for example. If you're
copying, then it's normal that you don't see the values you've written.
If you're using std::vector, I'd use G... |
7,318,170 | 7,319,467 | Unmanaged c++ DLL in C#... WINAPI and Pointers | I've been asked to intergrate webcam ZoneTrigger in my project. The SDK provided in the site is C++ also the sample. I've been able to get few functions to work. the place i've been stuck is a function where callback is done.
Code in sample c++ the callback function
ZT_SetCallbackProc(ZoneTriggerCallbackProc);
// in ... | Daniel's answer has the simple and quick route. If you don't want to run into problems (as the delegate can get collected by the GC resulting in an AccessViolationException) you will need to do the following.
The type/pinvoke declarations from Daniel (for completeness):
// int WINAPI ZoneTriggerCallbackProc(int Message... |
7,318,361 | 7,417,618 | Weird IDL error after migration to VS2010 | Here's a very simple IDL interface that we've used successfully under VS2008 (arguments list shortened for brevity):
interface Mailer
{
string findNode( [in] string requestedNode );
unsigned short addMessage( [in] string msg, [in] unsigned short kind );
};
We're migrating the solution to VS2010 SP1. Now we hav... | It appears that the IDL file, although present in the project, isn't used at all. VS2008 silently ignored it (as it would do for an unreferenced .h file).
For some reason, VS2010 tries to compile it even if it's not referenced anywhere else. And since the contents is totally buggy (string is indeed not a native IDL typ... |
7,318,362 | 7,318,581 | Linker error LNK2019 from 3rd party library | I am porting an old vc++6.0 application to vs2005, I am getting the following linker error and I have spent days trying to find a solution.
error LNK2019: unresolved external symbol _imp_CreateAwnService@52
referenced in function "public: int __thiscall
CMainFrame::CreateAsaNetworkServices(void)"
There is a 3rd p... | Looks like you're missing the import library for the dll, or the linker cannot find it, in the Linker -> Input -> Additional dependancies
The library paths can be set in Linker -> General -> Additional Library Directories
It may be that the header files try to automatically include the lib file using a #pragma, so you ... |
7,318,368 | 7,318,454 | Encrypting using user's password | I want to encrypt a given data using the log-in user's password on a windows machine using WINAPI. I've been looking for a function that uses a token (or something like that) but I couldn't find one.
Does anyone know how to do that?
Thanks! :-)
| I had written this answer earlier but then reconsidered, since I hadn't heard of the DPAPI before. However, upon some further consideration, I'd like to offer the following opinion. The important preface here is that it all depends on your needs, though. Two conflicting possibilities come to mind:
You want to offer yo... |
7,318,613 | 7,318,814 | C++ unmanaged DLL in c# | I've been asked to intergrate webcam ZoneTrigger in my project. The SDK provided in the site is C++ also the sample. I've been able to get few functions to work. the place i've been stuck is a function where char* is a parameter passed. I did a lot of digging and have come to know that MarshalAs has to be used...
the f... | I can't see where you are using ZT_TRIG_STRUCT, but that should be declared like this:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct ZT_TRIG_STRUCT
{
public int aSize;
public int CameraIndex;
public int SpotIndex;
public int SpotType;
[MarshalAs(UnmanagedType.ByValTStr, ... |
7,318,850 | 7,322,451 | Where can I get pkfuncs.h (and access to KernelIoControl)? | I'm trying to call KernelIoControl but can't find the header file pkfuncs.h anywhere.
I'm wondering if:
a) Is there a secret download I need?
b) Or is it not present because the device's SDK I'm using (Casio) does not include these libraries?
Also ... presumably it's WINAPI? I think I'll just dynamically link to it.
| In my searching I also found this page very useful on getting the IOCTRL_HAL_GET_DEVICEID:
It also details the DEVICE_ID structure, which is necessary to use the call:
#define IOCTL_HAL_GET_DEVICEID CTL_CODE(FILE_DEVICE_HAL, 21, METHOD_BUFFERED, FILE_ANY_ACCESS)
typedef struct _DEVICE_ID {
DWORD dwSize;
DWO... |
7,318,892 | 7,319,017 | std exceptions inviting unsafe usage? | It is recommended that you always throw something derived from std::exception and there are a few predefines specialisations such as std::runtime_error
std::exception's interface is given in terms of non-throwing accessors. Great. Now look at the constructor for std::runtime_error
class runtime_error : public exception... | I think your main problem is that you are doing catch(...) and translating to a std::runtime_error thereby losing all type information from the original exception. You should just rethrow with throw().
Practically, if you are short of memory you are likely have a bad_alloc exception thrown at some point and there's not... |
7,318,893 | 7,318,926 | C2440 Can't convert LRESULT to WNDPROC in C++ WinApi | I'm trying to write this win32 program with WinApi and I'm stuck because the tutorial I'm following seems to have a problem.
MainWindow.h:
class MainWindow
{
public:
MainWindow(HINSTANCE);
~MainWindow(void);
LRESULT CALLBACK WndProcedure(HWND, UINT, WPARAM, LPARAM);
// [...]
MainWindow.cpp:
MainWind... | replace
LRESULT CALLBACK WndProcedure(HWND, UINT, WPARAM, LPARAM);
by
static LRESULT CALLBACK WndProcedure(HWND, UINT, WPARAM, LPARAM);
The this pointer is a hidden parameter in your function call and by declaring it static the this pointer is not a parameter anymore and the signature of the two functions match.
|
7,319,195 | 7,392,799 | boost asio "A non-recoverable error occurred during database lookup" | I'm currently stress testing my server.
sometimes I get "A non-recoverable error occurred during database lookup" Error
coming from error.message()
error is sent to my handling function by boost::asio::placeholders::error called on the async_read method.
I have no idea what this error means, and I am not able to reprod... |
When it reads something, most of the time, it is doing some work on a
thread (coming from a pool), and write something synchronously back to
the user. (using boost write). Even since boost 1.37 claims that
synchronous write is thread safe, I'm really worried about the fact
that it is coming from this.
Emphasis added ... |
7,319,391 | 7,319,478 | How to search in a BYTE array for a pattern? | I have a Byte array :
BYTE Buffer[20000]; this array contains the following data:
00FFFFFFFFFFFF0010AC4C4053433442341401030A2F1E78EEEE95A3544C99260F5054A54B00714F8180B3000101010101010101010121399030621A274068B03600DA281100001C000000FF003457314D44304353423443530A000000FC0044454C4C2050323231300A2020000000FD00384B1E5310... | Since you're in C++, do it the C++ way:
char a[] = { 0, 0, 0, 0xFC };
char Buffer[20000] = ...
std::string needle(a, a + 4);
std::string haystack(Buffer, Buffer + 20000); // or "+ sizeof Buffer"
std::size_t n = haystack.find(needle);
if (n == std::string::npos)
{
// not found
}
else
{
// position is n
}
Yo... |
7,319,438 | 7,320,732 | How to synchronize visual studio projects while working as a team? | We have a problem that we're sure that it's already solved. Our research team in the university is developing a software using Visual Studio 2010. The software we develop is based on different open source tools, which have their own libraries in their own paths at each different computer.
The open source packages are c... | You should use CMake to generate Visual Studio project files. Commit only source, header, and the CMakeLists.txt.
Work with a seperate build path. For example, if your Project structure is like
Project\Src
Project\Doc
Project\......
create a build folder like
Project\build
and generate the VS-Solution and Project fi... |
7,319,494 | 7,319,561 | Overloading virtual functions of the same name from different base classes. Is it possible? | The title is probably confusing.
Suppose we have the following set up;
class A
{
public:
virtual void fn() = 0;
};
class B
{
public:
virtual int fn() {};
};
class C: public A, public B
{
};
Is there any way to define A::fn in class C?
| No. This is not possible. It will always conflict with either of the fn().
The syntax of fn() are different,
void fn(); // in A
and in B is,
int fn(); // in B
You have to make those syntax same in A and B to let C implement the fn(). Demo.
|
7,319,508 | 7,319,589 | On what does the size of an C++ object file depend? | Whenever we compile a c++ file, an obj file is generated. I want to know that on what factors does the size of the obj file depend?
Just to make my question more clear,
For example a c++ file contains a class declaration and this class has 1 integer variable as data member and also has some member functions. If i compi... | That depends on a million different factors and is entirely platform and compiler and settings dependent.
The object file has to contain all the assembly for function bodies for functions with external linkage, as well as all the global variables with external linkage. Anything with internal linkage may or may not warr... |
7,319,567 | 7,320,029 | Can I use template aliases as template template parameters? | Can I use template aliases as template template parameters?
template <template <typename...> class> struct foo {};
template <typename T> using simple_ptr = std::unique_ptr<T>;
foo<std::unique_ptr> a; // this doesn't work, std::unique_ptr has two parameters
foo<simple_ptr> b; // does this work?
| Yes, it is apparently allowed. According to the latest draft of the upcoming standard I could find, it is stated that
A template-argument for a template template-parameter shall be the name of a class template or an alias template [...].
However, alias templates seems very seldomly supported at the moment, so you mig... |
7,319,583 | 7,320,707 | Can't Use GetAsyncKeyState + Message Pump, SC_MONITORPOWER not Fully Working | I'm trying to make a program that can turn off the monitor with a key combination and turn it back on with another. The power button fell off, so the monitor pretty much stays on now. I noticed sending a WM_SYSCOMMAND with a WPARAM of SC_MONITORPOWER would probably do the trick, but in reality it wasn't.
First, I tried... | As tinman said, use RegisterHotKey.
To address your question, GetAsyncKeyState reads the current key state. GetMessage reads messages in a queue. They won't be synchronized. You should instead use GetKeyState which stays in sync with the message queue.
But yea, RegisterHotKey.
|
7,319,774 | 7,320,772 | memory pools: will they improve cache usage for structs larger than the cache line size? | As I understand it, memory pools should improve cache performance for objects commonly accessed together, if the objects are smaller than the cache line size - because then adjacent objects will likely be fetched into the cache at the same time.
But what about objects larger than the cache line size? Is there any bene... | Memory pooling makes sense if your app uses a huge amount of memory and starts to swap. Then, if the objects lie adjacent to each other, they will be paged in and out together.
|
7,319,810 | 7,320,054 | Throwing during unwinding -- why does this example work? | Consider this:
void thrower () {
throw "123";
}
struct Catcher {
~ Catcher () {
try {thrower ();}
catch (...) {}
}
};
int main () {
try {
Catcher c;
throw 1.23;
}
catch (...) {}
}
This compiles and runs without calling terminate on gcc 4.3, but according to the s... | Different emphasis:
when the exception handling mechanism, after completing evaluation of the expression to be thrown but before the exception is caught (15.1), calls a user function that exits via an uncaught exception... terminate shall be called
thrower() is a user function that exits via an exception but it is no... |
7,320,122 | 7,320,196 | In my code scoped_ptr points to a stack variable -- does that extend the lifetime of the stack variable? | I wanted to know if the following code is well formed
if ( nChildLines == 0 )
{
nChildLines = 1;
Tag tempTag = attachmentlines.tag();
cfgChildLines = &tempTag;
}
Here, tampTag is some object. And cfgChildLines is a scoped pointer to that object declared outside of the 'if' block.
Now my question is, ... | Important to remember that taking an address in C++ does NOT guarantee any protections that that address continues to point to something valid. There's no reference counting built into the language (thats why we had to invent scoped_ptr/shared_ptr/etc).
Keeping that in mind, we can look in more detail at your situation... |
7,320,188 | 7,327,467 | Divide and conquer algorithms to find the maximum element of an array | I am trying to understand how the following algorithms works.
#include <iostream>
using namespace std;
int maxsimum(int a[], int l, int r) {
if (l == r)
return a[l];
int m = (l+r)/2;
int u = maxsimum(a,l,m);
int v = maxsimum(a,m+1,r);
return u>v?u:v;
}
int main() {
int a[] = {34,2... | Your confusion is understandable: the algorithm as written contains a couple of bugs. It accesses memory past the end of a, which is very, very bad. Also, the test whether a range contains only one element is incorrect. If not addressed, this leads to a stack overflow.
The way the maximum function is called suggests th... |
7,320,424 | 15,186,314 | c++ win32 Simulate Keypress with DirectInput | How can I simulate a keypress with DirectInput? I currently have the initialization (but I'm not sure is it good or not):
#include <dinput.h>
#pragma comment (lib, "dinput8.lib")
#pragma comment (lib, "dxguid.lib")
LPDIRECTINPUT8 din; // the pointer to our DirectInput interface
LPDIRECTINPUTDEVICE8 dinkeyboard; ... | SendInput
SendInput lets you simulate key presses. You have a choice of identifying keys using either virtual key codes or scan codes (see KEYBDINPUT.dwFlags). Apparently, DirectInput ignores virtual key codes but does process scan codes.
In short, use SendInput with scan codes and DirectInput will respond.
Intercept... |
7,320,537 | 7,321,036 | Eclipse CDT: How can I change background color of tooltip in editor? | I'm using eclipse for coding C++ and Java. When declaration or definition is shown, background is black. It happens only in C++ srouce file. I dont have this problem while editing Java source files.
I have installed Eclipse Color Theme. I'm not able to find where i can set background color of this window. I have been s... | I had this problem because I installed this plugin. I tried out the themes but when I decided on the original and swapped back to it the tool tips were broken in this fashion. Unfortunately the only way I managed to fix it was by "reinstalling" eclipse.
|
7,320,766 | 7,320,902 | Where can I find documentation on C++ memory alignment across different platforms/compilers? | I'm looking for a good (comprehensive) doc about memory alignment in C++, typical approaches, differences between compilers, and common pitfalls. Just to check if my understanding of the topic is correct and to learn something new.
This question is inspired by my answer to another question where I used following constr... | You can find an overview on wikipedia.
More in depth on the IBM site: Data alignment: Straighten up and fly right
|
7,320,840 | 7,320,929 | Good idea to seed a RNG each time you use it? | I'm using the Mersenne twister algorithm to shuffle playing cards. Each time the deck needs to be shuffled I seed it with time(NULL) + deckCutCardNumber which is where the user chose to cut the deck. Would I get better results from only seeding it the first hand and continuing to generate them with the same seed or is ... | Assuming the user doesn't mess with the clock (or carefully reduce their cut number by exactly the time that has passed), they'll never see a repeated state of the PRNG anyway, so it doesn't make much difference what you do. You'll get a reasonable distribution out of the Mersenne Twister from any seed value[*], and at... |
7,321,118 | 7,321,150 | Efficient way to convert a 16-bit short array to a 32-bit int array? | What is the most efficient way to convert an array of unsigned short numbers (16 bits per value) into an array of unsigned ints numbers (32 bits per value)?
| Copy it.
unsigned short source[]; // …
unsigned int target[]; // …
unsigned short* const end = source + sizeof source / sizeof source[0];
std::copy(source, end, target);
std::copy internally choses the best copying mechanism for given input types. In this case, however, there’s probably no better way than copying the ... |
7,321,144 | 7,321,401 | What Turing complete macro languages are available for C/C++ | Preamble
One of the major points which Lispers claim as a bonus over more "mainstream" languages is that the macro language is actually Turing complete (I cannot recall if this was Paul Graham in On Lisp or if it was Conrad Barski in Land Of Lisp)1, and to an outsider, at least, this seems true -- pre-processor directi... | C macros are in fact Turing complete, if processed more than once. Check out this related question and in particular the Turing machine implementation linked to in the accepted answer.
But yes, this is cheating. The solution used there strongly implies that C macros really aren’t Turing complete.
|
7,321,188 | 7,321,234 | conversion from float to integer | i have following simpled algorithm for calculation roots of quadratic equation
#include <iostream>
#include <math.h>
using namespace std;
int main(){
float x,x1;
x=0;x1=0;
int a=1;
int b;
int c;
cout<<"enter the second term:"<<endl;
cin>>b;
cout<<"enter the third term:";
cin>>c;
... | ^ is the bitwise xor operator, not the power, as you probably think. To raise a number to an arbitrary power, use std::pow (from the standard header cmath). For powers of two, you can just use x * x.
|
7,321,212 | 7,322,285 | poppler library for Android app (NDK) will be possible instead of xpdf? | I need to create an Android app that shows pdf files and I want to use xpdf or poppler library. This question is only about these 2 choices. I already know how to exploit poppler-qt4 so I'd prefer to use it but I fear that compiling it with NDK will yield a huge binary. Is it right? Should I use xpdf?
The question is: ... | From the official website:
Poppler is a PDF rendering library based on the xpdf-3.0 code base.
So I guess the differences might not be that huge.
Integrating popplar might be difficult though, since it does not provide a front-end for the android GUI system.
I'm not sure about xpdf, though.
EDIT:
Will I have troubl... |
7,321,513 | 7,321,802 | Do I understand C/C++ strict-aliasing correctly? | I've read this article about C/C++ strict aliasing. I think the same applies to C++.
As I understand, strict aliasing is used to rearrange the code for performance optimization. That's why two pointers of different (and unrelated in C++ case) types cannot refer to the same memory location.
Does this mean that problem... | The problem here is not strict aliasing so much as structure representation requirements.
First, it is safe to alias between char, signed char, or unsigned char and any one other type (in your case, unsigned int. This allows you to write your own memory-copy loops, as long as they're defined using a char type. This is ... |
7,321,676 | 7,321,752 | structure versus classes | // By using structure :
struct complex {
float real;
float imag;
};
complex operator+(complex, complex);
main() {
complex t1, t2, t3;
t3 = t1 + t2;
}
complex operator+(complex w, complex z) {
statement 1;
statement 2;
}
// By using class :
class complex {
int r... |
...when the overloaded operator function is a member function in both
cases i.e structure as well as class...
What makes you say that? That's not true.
In case of struct in your example, overloaded operator function is not a member. This is why it requires 2 parameters.
So, the difference has absolutely nothing t... |
7,321,993 | 7,322,098 | Reference to Function syntax - with and without & | What's the difference between
typedef void (&FunctionTypeR)();
vs
typedef void (FunctionType)();
Is the second also a reference to function? Is FunctionTypeR equivalent to FunctionType& when used as the type of an argument?
For
void foo(FunctionType bar)
Does the runtime makes a copy of the argument bar (a functi... | The difference is that you cannot create objects of function type, but you can create of objects of function pointer type, and function reference type.
That means if you've a function, say f() as:
void f(){}
then here is what you can do, and what you cannot do:
FunctionType fun1 = f; //error - cannot create object o... |
7,322,070 | 7,322,123 | Why VC++ IntelliSense doesn't refresh error list? | Why VC++ IntelliSense doesn't refresh error list?
There's an error in the code. IntelliSense shows it up. I fix it, and press F7 to re-compile, the compilation result is successful. But now IntelliSense doesn't refresh the error list, it still shows the former error, even after pressing 10 times F7 and F5 to start deb... | Try removing your intellisense database file (.NCB file).
If the problem persists then you might have a too big project...
In my previous company we solved this by using intellisense of Visual Assist.(http://www.wholetomato.com/)
Too bad microsoft has a very unreliable intellisense database.
|
7,322,147 | 7,322,207 | What is the range of OpenGL texture ID? | I have an object which owns a property Texture_ID. I need to initialize the value for Texture_ID in constructor, so I want some value unused by OpenGL to present that the texture is not yet set.
I don't know whether zero (0) is a good value? If there is a range that OpenGL applies to texture IDs, I want a value out of... | 0 is the value you're looking for (to represent an unset texture ID/uncreated texture), as 0 is never a valid texture ID.
|
7,322,585 | 7,322,620 | Class assignment operator= question | Say I have two classes, in two different headers, called:
class TestA
{
public:
int A;
};
class TestB
{
public:
int B;
};
And I want to give them both an assignment operator to each other, so it's like:
class TestB; //Prototype of B is insufficient to avoid error with A's assignment
class Tes... | You cannot have the function definitions in your files as written as that will require a circular dependency.
To solve, forward declare the classes and put their implementation in a separate files.
A's header file:
// A.h
// forward declaration of B, you can now have
// pointers or references to B in this header fil... |
7,322,781 | 7,322,936 | How to link static library into static library in Eclipse CDT | I have 3 projects A, B and C.
A is universal and used by B and eventually C.
B is a bit more special and up to now only used by C.
Now as I want A and B to be reused as much as possible I thought of both being static libraries.
So I link A and B to static libraries and C to an executable, but when I want to link C
it g... | a static library cannot be linked with another static library. I think because a static library is not an executable code and so full linking process (mainly references resolution) is not done. It's done only for dynamic libraries and executables.
|
7,322,960 | 7,323,015 | Can I assign multiple threads to a code section in OpenMP? | I'm looking for a way to execute sections of code in parallel using multiple threads for each section. For example, if I have 16 threads and two tasks, I want 8 threads each to simultaneously execute those two tasks. OpenMP has several constructs (section, task) that execute general code in parallel, but they are singl... | You can do this using nested parallel regions.
omp_set_nested(1);
#pragma omp parallel num_threads(2)
{
if (omp_get_thread_num() == 0){
#pragma omp parallel num_threads(8)
{
// Task 0
}
}else{
#pragma omp parallel num_threads(8)
{
// Task 1
}
}
... |
7,323,096 | 7,323,221 | Dealing with pointers that may not point to anything | I have a set of objects in a vector of pointers to their baseclass held inside a manager:
std::vector<object*> objectVec;
Classes may wish to spawn one of these objects using the Add() method in the manager. The problem is that they then subsequently need to set or update these objects themselves. I've decided to have... | You likely want weak_ptr and shared_ptr. shared_ptr is a general smart pointer class. weak_ptr is an observer of shared_ptr. When all the references of the shared_ptr go away, instances of weak_ptr "become null" and are easier to deal with than a pointer to a deleted object.
These classes come with Boost.
http://www.... |
7,323,282 | 7,329,513 | Setting a QDialog to be an alien | In a standalone GUI application where I don't have a windowmanager nor a composite manager I want to display a QDialog to the user to ask for values.
The dialog is quite big, so I want to make it translucent so that the user can look through it to see what happens in the application while the dialog is shown.
The prob... | I don't know of any way of turning a QDialog into a normal child widget. Looking at the Qt for X11 code, I can't figure out a way of not setting the Qt::WindowFlags passed to the QWidget (parent) constructor so that it would be a plain widget and not a window of its own (but I could be wrong, didn't spend a lot of time... |
7,323,288 | 7,323,420 | How does wcout work? | I noticed a weird problem while using wcout in a console application.
After calling a certain function, the rest of the wcout calls did not work at all. i.e. the output statements did not appear on the console.
I noticed that in the function, I had used a wide character array which was never assigned.
WCHAR wArray[1024... | This example invokes undefined behavior.
operator<<(std::wostream&,const wchar_t*) expects the buffer to be null terminated, and stop printing characters when it reaches the first L'\0' character. If the buffer happens to contain a null character (L'\0'), then the code will run "correctly" (although the output is unpr... |
7,323,760 | 7,323,867 | What factors can lead to Win32 error 665 (file system limitation)? | I maintain an application that collects data from a datalogger and appends that data to the end of a binary file. The nature of this system is that the file can grow large (> 4 gigabytes) small steps at a time. On of the users of my application has seen cases on his NTFS partition where the attempts to append data fa... | This sounds like you've reached a limit in the fragmentation of the file. In other words, each flush is creating a new extent (fragment) of the file and the filesystem is having a hard time finding a place to keep track of the list of fragments. That would explain why copying the file helps -- it creates a new file wit... |
7,323,895 | 7,323,966 | Sound problem with c++ video player | I have a c++ made video player and for a reason I can't understand only some of the files (.avi) are playing with sound, the others only have the visual.
I think it's because these videos use a codec that the program doesn't support. Is there a way to "integrate" an other codec so all my avi files will have sound ?
| Open them in VLC player and find the codec type of the audio, Check if your player supports that codec type. Adding the new codec type would depend on how your plug-able your video player code is
|
7,324,034 | 7,335,232 | Write a float with full precision in C++ | In C++, can I write and read back a float (or double) in text format without losing precision?
Consider the following:
float f = ...;
{
std::ofstream fout("file.txt");
// Set some flags on fout
fout << f;
}
float f_read;
{
std::ifstream fin("file.txt");
fin >> f;
}
if (f != f_read) {
... | If you don't need to support platforms that lack C99 support (MSVC), your best bet is actually to use the %a format-specifier with printf, which always generates an exact (hexadecimal) representation of the number while using a bounded number of digits. If you use this method, then no rounding occurs during the conver... |
7,324,169 | 7,324,231 | Current C++ Best Practices & IDEs | I've been living under a Java rock for about 5 years now. I suddenly have the need to write a Windows-only program that I believe would be best suited as either pure C++/Windows or C++.NET (I'm not sure which yet). The reason is because I need to do all sorts of very OS-specific (Windows-specific) operations that would... | Visual Studio 2010 or free alternative Visual Studio Express
http://www.microsoft.com/express
|
7,324,285 | 7,324,380 | Equivalent of this Python random number generator in C++? | Just switch from Python to C++ and I begin to re-write my Python tools in C++ for better understanding, but can't solve this one...
This function will generate range of random numbers, for example "randomRange(12)" may return range of 12 numbers like "823547896545"
Python:
def randomRange(n):
range_start = 10... | You'll have trouble getting good randomness with high values of n, but:
#include <math.h> // for pow()
#include <stdlib.h> // for drand48()
long randomRange(int n)
{
// our method needs start and size of the range rather
// than start and end.
long range_start = pow(10,n-1);
long range_... |
7,324,471 | 7,327,213 | Direct3D11(C++): Rendering (basic) question | I've been following a book about basics for game programming with D3D11. I now understand the absolute basics of Direct3D :)
but... I have a question.
In the book, I always had to make one demo at a time. Now, I'm trying to make a 2D game with it. Since I don't want to get used to bad habits so I need your advice.
In t... | The simple answer is yes, you should create multiple vertex buffers, input layouts, shaders, etc. and set the appropriate ones before each corresponding draw call. This will work and is reasonably efficient (should be efficient enough for a 2D game on modern hardware).
Things tend to get a bit more complicated in a ful... |
7,324,479 | 7,324,498 | C++ Strategy pattern | In the past, I have seen the strategy pattern explained as a mechanism which allows the user of a function/class to provide their own functionality for that function/class.
I had always been taught that the way to implement the pattern was by taking function pointers into your classes/functions and calling them interna... | You simply have to use inheritance in languages without function pointers (read: Java).
Personally, I would prefer std::function over raw function pointers, because it accepts a wider range of arguments and allows you to maintain state in the strategy object.
Also, if you already know the strategy at compile-time, you ... |
7,324,715 | 7,326,149 | How to edit and overwrite specific location in file in C++ | I am making an airline reservation software and I don't know much about the Visual C++. I am using the simple compiler "TCWIN45". In my program I wish to use file handling and I am succeed to save all the inputs in text file. i need to add search option and modification option. if user choose search and Enter the name ... | Ali, this can be done in a flat file if you really want to not use a database. The trick, is to either: 1.) have all records the same size OR 2.) have a "record header" that provides "enough" information to be able to unserialize the record from the hard disk. If you store different kinds of records, "enough" informa... |
7,324,818 | 7,325,089 | High-traffic service | What is the fastest type of inter-process communication on Windows? We need to transfer data with high speed to our "system-wide" scanning component. What's the best type of application for that component? Windows service?
Performance is crucial. Implementation will be developed in C++.
| Your fastest IPC will be shared memory/memory mapped files. This is done via CreateFileMapping/OpenFileMapping/MapViewOfFile/UnmapViewOfFile and a few other Win32 calls.
http://msdn.microsoft.com/en-us/library/aa366551%28v=vs.85%29.aspx
|
7,324,843 | 7,324,849 | Why use endl when I can use a newline character? | Is there a reason to use endl with cout when I can just use \n? My C++ book says to use endl, but I don't see why. Is \n not supported as widely as endl, or am I missing something?
| endl appends '\n' to the stream and calls flush() on the stream. So
cout << x << endl;
is equivalent to
cout << x << '\n';
cout.flush();
A stream may use an internal buffer which gets actually streamed when the stream is flushed. In case of cout you may not notice the difference since it's somehow synchronized (tied... |
7,324,857 | 7,324,903 | Background-image for QLineEdit | How to set background image for QLineEdit? The following style sheet doesn't work
QLineEdit {
background-image:url(:/images/13.png);
}
| QLineEdit {
border: 1px solid #000000; //image work with this line and didn't work with out))
image: url(:/images/13.png);
}
|
7,324,904 | 7,324,955 | Remove elements from list in a loop without break | In the code of my game, I want to remove some elements from a list,
which happens in a loop.The only problem I have is, when I use
list::erase I have to break after that function because I think
the list becomes "outdated". This causes a little flicker and I want to
try to remove it.
The current code is this:
for(list<... | you should do:
it = arrows.erase(it);
//
list<Arrow*>::iterator it = arrows.begin();
while (it != arrows.end())
{
Arrow* a = (*it);
if(a->isActive())
{
a->update(); ++it;
}
else{ // delete (a); ???
it=arrows.erase(it);}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.