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 |
|---|---|---|---|---|
6,722,179 | 6,722,197 | Correctly delete pointers in std::list allocated elsewhere |
Possible Duplicate:
Does std::list::remove method call destructor of each removed element?
I have a SpriteHandler class that allows the user to register a pointer to a Sprite object for drawing, all it does is access methods on the object. I wanted to write a safety catch that automatically deleted the memory associ... | If you want safety and implicit resource cleanup, do not use raw pointers, use smart pointers!
The problem with STL containers is:
If the contained object is a pointer STL containers DO NOT take ownership of destroying it.
You will have to explicitly call delete on each contained pointer to delete the content it is p... |
6,722,244 | 6,723,449 | Undefined reference to LONG_PTR , Digital Mars C++ compiler problem | I am using the Win Api. My program uses LONG_PTR. It compiles fine with both MinGW and Borland C++ Compiler. But when I try to compile it using the Digital Mars C++ Compiler it gives an error undefined reference to LONG_PTR. Do I have to link extra libraries for DMC, or does the DMC not support WinApu fully, or is LONG... | Most likely, the Windows headers simply don't have a correct #ifdef for that compiler. MSDN lists the types of all Windows API types, so it should be easy for you to look it up and provide the correct type.
|
6,722,333 | 6,722,389 | Why overloading causes ambiguous call if unsigned is used? | void foo(int,int) {}
void foo(int ,float) {}
void foo(float,int) {}
void main()
{
unsigned int i = 10;
unsigned float f = 1.0; //line 5
foo(i,f); // ambiguous call error
}
replacing line 5 by
float f = 1.0;
makes the program work. Why is it so?
I am working on visual studio 2005.
| There is no such data type as unsigned float. Pay attention to compiler warnings; if you're not getting any bump up the warning level. From running this example on Visual Studio 2010 it looks like the compiler ignores the float keyword in the declaration
unsigned float f = 1.0;
This makes f an unsigned int. Since you... |
6,722,568 | 6,724,113 | Template - class that uses int, short or float when necessary | I want to write a class that manages euclidean vector and that store its initial point using short, int, long or float. I thought to create a template like this:
template<class unit> class EVector
{
private:
unit x;
unit y;
public:
EVector();
setX();
setY();
};
So user creates an EVector choosi... | For addition, you can use my promote implementation:
template<typename A, typename B>
EVector<typename promote<A, B>::type>
operator +(EVector<A> const& a, EVector<B> const& b) {
EVector<typename promote<A, B>::type> ev;
ev.setX(a.getX() + b.getX());
ev.setY(a.getY() + b.getY());
return ev;
}
For types double... |
6,722,643 | 6,722,654 | Why do we need to delete allocated memory in C++ assignment operator? | Why do we need the delete statement?
const MyString& operator=(const MyString& rhs)
{
if (this != &rhs) {
delete[] this->str; // Why is this required?
this->str = new char[strlen(rhs.str) + 1]; // allocate new memory
strcpy(this->str, rhs.str); // copy characters
this->length = rhs.... | This is not a copy constructor, it's the assignment operator. You need the deleted because the object being assigned is holding already a previous value.
This code is also not really good because first deletes the old value and then allocates the new one... but the allocation may throw an exception and in this case the... |
6,723,881 | 6,724,372 | How to call an unmanaged C++ function with a std::vector<>::iterator as parameter from C#? | In unmanaged C++ I have a function which I'm trying to call from C#. This C++ function is as follows:
typedef std::vector<Point> Points;
typedef std::back_insert_iterator<Points> OutputIterator;
namespace MYNAMESPACE{
DLLEXPORT OutputIterator convexHull(Points::iterator first, Points::iterator last, OutputIterat... | Passing C++ types through P/Invoke is not going to work. You don't know their layout and nothing guarantees they won't change. P/Invoke is really only meant for inter-operating with C.
One option is to use C++/CLI instead of C++. This won't be portable (only supported with VC++/Windows), but it might be the easiest ... |
6,723,905 | 6,723,991 | What event is sent by a click on the "X" close button for an MFC balloon tooltip? | I am working on a very big and complex application for Windows written in C++ and using MFC.
I am working on this bug, where if a user presses on a balloon tooltip, it won't close, only after a timeout.
The thing is that I got the NIN_BALLOONUSERCLICK event and managed to close the tooltip, but I can't seem to catch th... | The reason you can't find any such event is because one does not exist. It is not possible to distinguish between the balloon being closed because the user clicked somewhere on it and the balloon being dismissed because the user clicked specifically on the close ("X") button.
More information can be found in this artic... |
6,724,062 | 6,724,568 | h and hpp problem, wrong order of including | I am compiling a large project containing >500 classes. After compiling VS 2010 there have been no problems. When using g++ (Code:: Blocks / Netbeans) under Windows the code will not compile with the following error:
library/source/algorithms/file/../../algorithms/graph/../algebra/../spheredistance
/file.hpp:31:51: fa... |
However, this file exists in the specified path
No, it does not.
Although you're right in that cyclic inclusion can lead to some misleading error messages, this is not one of them.
One thing to bear in mind is that the resolution of inclusion paths is implementation-defined (2003:12.8/1), which may be why you're seei... |
6,724,072 | 6,724,308 | doubt about way to lock a boost mutex | boost::recursive_mutex m;
m.lock();
versus
boost::lock_guard<boost::recursive_mutex> lock( mutex_ );
Is there an advantage to use the first Form? Does the second form only provide RAII mecanism, or are there others advantages ?
| The advantage of using lock_guard is that it will release the lock when it goes out of scope. This eliminates the need to manually release the lock and reduces the chance of forgetting to do so.
boost::recursive_mutex mylock;
{
boost::lock_guard<boost::recursive_mutex> lock( mylock );
// do something
if... |
6,724,078 | 6,724,093 | luabind 0.9.1 iterator always only pop the last object | all. I got a stranger problem by using luabind to read a array from lua script.
The lua script looks like this:
root =
{
id = 1,
id = 2,
id = 3
};
and the c++ code is looks like this:
luabind::object data_root = luabind::globals(L)["root"];
for (luabind::iterator i(data_root), end; i != en... | There aren't multiple elements of root, it only has one. You assigned the key id to three different values, but the key only exists once and only has one value associated with it, so you basically only ever said root = { id = 3 }.
|
6,724,171 | 6,724,193 | How to translate such PHP code using CURL into C/C++? | I decided to implement OpenID login into my C++ server. I looked at list of avaliable C++ OpenID clients and found only one popular libopkele. But its requirements seem quite way 2 much for my simple server which has its own xml parser, uses boost for regexps and so on.
So I want to create simple openID client in C++,... | cURL has a C API: link. You can use this from C++ too.
It shouldn't be difficult to rewrite the function you gave when you use the cURL API.
|
6,724,260 | 6,727,473 | FMOD, Beats Per Second | Using FMOD (interactive audio middle ware), is it possible to calculate the Beats Per Second of a track in real time as it is playing?
I am unable to find much information about this, it would be very useful. Will be using c# but will be able to translate.
Thanks
| FMOD doesn't provide any mechanism to calculate beats per minute, you would need third party software to achieve that.
|
6,724,280 | 6,725,923 | correct use of boost::wait boost::condition | boost::condition cond;
boost::recursive_mutex mutex;
for(;;)
{
D * d = nullptr;
while( cb.pop(d) )
{
}
boost::lock_guard<boost::recursive_mutex> lock( **mutex** );
cond.wait( **mutex** );
}
while(1)
{
getchar();
for( int i = 0 ; i < 1000 ; ++i )
{
cb.push(new D(i)); ... | Assuming you are using a recent version of boost, boost::condition is the same thing as boost::condition_variable_any, which I believe is the same thing as std::condition_variable_any.
If all that is true, or at least approximately true, your code should compile, but will probably deadlock if you call cond.wait(mutex) ... |
6,724,483 | 6,724,587 | How to set the font of the entire application in win api? |
Possible Duplicates:
How to set default font for all the windows in a Win32 Application?
Which Font is the default for MFC Dialog Controls?
I hate default Windows Api Window Font (it is the default system font , i think). I know how to change the font of an individual child, say a button. But isn't there a way to ch... | I explain all of this in quite a bit of depth here: Which Font is the default for MFC Dialog Controls? Definitely required reading for any Win32 developer who cares about getting the UI right.
There's no way to set the font for an entire application. The best thing you can do is set the font for a parent window and tak... |
6,724,671 | 6,724,819 | C++ valarray/template classes not working | this is my first post here but I've been a frequent reader of various topics here.
Now I'm stuck with a programming issue with c++, its basically a template class called "Pair" which should contain 2 valarrays of ints and then be included in another class called Wine. Problem is I'm not getting either the constructors ... | What's wrong: Well, honestly, where do I start?
Firstly, there is a std::pair structure. Secondly, the valarray stuff was a total mistake and not at all used anymore. Thirdly, const char*, int[] arguments? Owch. Can you say buffer overrun and memory corruption? Fourthly,
int Wine::sum()
{
int b;
int ar = 0... |
6,724,693 | 6,724,720 | How to print values in multiset? | How to access the values stored in the data structure multiset, C++?
for (int i = 0; i < mlt.size; i++)
{
cout << mlt[i];
}
| If T is the type contained in your multiset,
for (std::multiset<T>::const_iterator i(mlt.begin()), end(mlt.end());
i != end;
++i)
std::cout << *i << "\n";
|
6,724,753 | 6,724,830 | How to detect if an ellipse collides with an another ellipse / rectangle | I want to detect if ellipse collides with another ellipse and rectangle. How I can do it?
I'm writing in C++. I want to use it for a game.
| If this is for a game, then exactness should not be an issue.
Treat your ellipse as a polygon, that is, choose N evenly distributed points on your ellipse and treat is as a polygon. Adjuct N to the level of the desired correctness.
Now you need to test if a convex polygon collides with a rectangle. And the latter is a... |
6,724,977 | 6,750,629 | Comparisons of arbitrary arithmetic types: does anyone know an implementation? | While writing several math utilities I bumped into need to implement generic utility that can perform comparisons between any two fundamental arithmetic types. As I began coding, it became clear that this operation is not as straightforward as it seems, since I need correct handling of corner cases, especially when the... | You may want to look into GNU's MP Bignum library at http://gmplib.org/. From their page:
GMP is a free library for arbitrary precision arithmetic, operating on
signed integers, rational numbers, and floating point numbers. There
is no practical limit to the precision except the ones implied by the
available me... |
6,725,035 | 6,725,364 | What would be Boost::regexp analog for PHP`preg_match_all`function? | So I have such php function I want to translate to C++:
protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
{
preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
preg_match_all("#<{$tag}[^>]*$valueName=['\"]... | Something like this:
boost::optional<std::string> htmlTag(const std::string& content,
const std::string& tag, const std::string& attrName,
const std::string& attrValue, const std::string& valueName)
{
const std::string
expr1 = boost::format("#<%1[^>]*%2=['\"].*?%3.*?['\"][^>]"
"*%4=[... |
6,725,130 | 6,725,158 | No linker error when global variable declared static in the header file |
Possible Duplicate:
Static variables in C++
// x.h
int i = 3;
// x1.cpp
#include"x.h"
//...
// x2.cpp
#include"x.h"
//...
Above code will give linker error. However If I declare,
//x.h
static int i = 3;
It doesn't give linker error in gcc, even we have the same #include! Are we creating different static int i; f... |
Are we creating different static int i; for every .cpp file ?
Yes
Will it cause any silent linking bug (due to same name)?
No. Due to static, they have different names.
If this isn't the behavior you want, you need to use extern in the header file, and allocate the variable in one translation unit (.cpp file)
|
6,725,287 | 6,725,328 | Change SDL background | Is there any way to change the color of an empty SDL window to be white instead of black? I don't want to change any default settings. I'm just trying to change it for this particular program that I'm writing. I don't want to use an image file, but if I have to, I will.
I don't know if this matters, but I'm using SDL_S... | Acquire the surface from your Window using surf = SDL_SetVideoMode(...) and then do
SDL_FillRect(surf, NULL, 0xFFFFFF); // 0xFFFFFF = white in RGB, NULL = full window
SDL_Flip(surf);
|
6,725,617 | 6,725,653 | Linker error with template class | I am trying to implement particle system using my custom template linked list class and getting linker error:
Error 3 error LNK2019: unresolved external symbol "public: struct Node<class Particle> * __thiscall LinkedList<class Particle>::Pop(void)" (?Pop@?$LinkedList@VParticle@@@@QAEPAU?$Node@VParticle@@@@XZ) refe... | Did you define your Pop function in a source(e.g. .cpp) file, rather than the header file? You can't do it that way with templates. You need to provide the function definitions in the header files. The definition needs to be visible at the point of instantiation.
|
6,725,706 | 6,725,733 | order of evaluation of function parameters | What will be printed as the result of the operation below:
x=5;
printf("%d,%d,%d\n",x,x<<2,x>>2);
Answer: 5,20,1
I thought order is undefined yet I found above as interview question on many sites.
| From the C++ standard:
The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified.
However, your example would only have undefined... |
6,725,772 | 6,725,831 | ReleaseStringUTFChars gives free(): invalid pointer: 0x0841a744 *** |
I have a library in c++ and I am writing JNI wrapper functions to allow me to call it from JAVA. I have got a lot of different functions working but I am having a problem with one in particular.
The function I am trying to wrap looks like:
void Set_Name(std::string invar)
I have matching calls to GetStringUTFChars a... | You first acquire the pointer with
const char *pPp_invar2 = p_jEnv->GetStringUTFChars( invar, NULL );
But then you reassign the pointer with
pPp_invar2 = pPp_invar->c_str();
You must first first release the memory, then reassign the pointer.
Also, you don't need to allocate pPp_invar with new and then delete it, a si... |
6,725,887 | 6,726,000 | help with c++ classes, pointers n such | I have a project where I'm implementing Dijkstra's shortest path algorithm using C++ classes. It uses OpenGL but that is surely separate from my problems. I need some insight on what I'm doing wrong in my Dijkstra class method. Here is my relevant code:
class Node {
public:
GLfloat x, y, z;
int num... | You should use the '->' operator when accessing data through a pointer. Otherwise you should use the '.' opearator.
For example these following lines are identical
Node *node = &q.front();
(*node).link1->distance = 1;
node1->link1->distance = 1;
As for your compilation problems, the problem is with how you are access... |
6,726,119 | 6,726,174 | Attempting to swap pointers in vector of pointers after a few layers of abstraction | So I have a vector of pointers holding a baseclass. I create two elements inside the vector and then attempt to swap them after a few layers of abstraction. Currently this causes the compiler to explode and throw several errors inside move.h that look like this:
*c:\program files (x86)\codeblocks\mingw\bin\../lib/gcc/m... | You're trying to swap objects of type Base.
slottemp->connected is of type Base *, so by swapping *slottemp->connected, you're swapping two Base &. Since there's no std::swap overload for Base &, the compiler falls back to the default, which goes something like this:
template <class T> void swap ( T& a, T& b )
{
T c(... |
6,726,315 | 6,726,345 | vector and array passing error | I'm writing a program based on the multi-chain Metropolis algorithm to find minimum energy parameters for a given function. This program basically runs two times:
First multi-chain burn-in run which sweeps the parameter space and stops when a given convergence criteria is met;
Exploratory run which samples the various... | int Step(double * current_energy, vector<double> & energy)
should be
int Step(double current_energy, vector<double> & energy)
Edit:
After the OP's comment I suggest this;
int Step(double& current_energy, vector<double> & energy)
^^^^
in this case you can change current energy without any pointer synt... |
6,726,473 | 6,726,935 | C++ forbidding setting char* and char[] from const char* | Here's the code. I have no idea why it doesn't recognize that it needs to copy the memory, and I can't force it to.
string message="The quick brown fox jumped over the lazy dog.";
vector<char*> words;
while(message.length()>0){
char wtf[message.substr(0,message.find(" ")).c_str().length()]=message.substr(0,... | How to break text into words (the easy way)
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::string message="The quick brown fox jumped over the lazy dog.";
std::vector<std::string> words;
std::stringstream stream(message); ... |
6,726,499 | 6,731,121 | This python code in C/C++ | I have this code:
#!/usr/bin/python
import urllib
print 'Insert page to download:'
page = raw_input()
filehandle = urllib.urlopen(page)
myFile = open('file.html','w')
for lines in filehandle.readlines():
myFile.write(lines )
myFile.close()
filehandle.close()
This basically just downloads the inputed webpage ... | I second libcurl, that is what I usually use for my quick and dirty solutions.
Usually when you program within a desktop environment (like GNOME and KDE) , you can use functionality from that environment that is made to be used within the GUI and is easier to use with the file chooser window, progress-bar et.c.
If you ... |
6,726,689 | 6,726,723 | c++ elusive segmentation fault | Im working on this bit of code and I keep getting a segmentation fault. For the life of me I cant figure out why, I know a segmentation fault is when you try to follow a null pointer, but the thing is, in my code "u->previous" isnt null, neither is "u", I checked. If I change the condition in the while loop to (u != N... | That error isn't just for null pointers, it is a pointer that points to anything invalid. That can be null, but it can also be memory that was freed.
|
6,726,772 | 6,739,825 | MVP matrix not working outside of shader? | Odd problem here, I've been converting my current project from Qt's native matrix/vector classes to Eigen's, but I've come across an issue that I can't work out.
I calculate the MVP for the shader thus:
DiagonalMatrix< double, 4 > diag( Vector4d( 1.0, 1.0, -1.0, 1.0 ) );
scrMatrix_.noalias() = projMatrix_ * diag * camM... | Well I sussed it out, you need to scale the XYZ axes of the resulting vector by the W axis scale factor (clues in the name...).
It's amazing how much Qt and OpenGL do in the background for you.
|
6,726,805 | 6,726,818 | Replace an element into a specific position of a vector | I want to replace an element into a specific position of a vector, can I just use an assignment:
// vec1 and 2 have the same length & filled in somehow
vec1;
vec2;
vec1[i] = vec2[i] // insert vec2[i] at position i of vec1
or I have to use insert():
vector<sometype>::iterator iterator = vec1.begin();
vec1.insert(iter... | vec1[i] = vec2[i]
will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i
v1.insert(v1.begin()+i, v2[i])
|
6,726,995 | 6,727,019 | Floats being rounded in C++ and I don't understand why | I am very confused about this... Here is an extract from my code..
float m = 0.0, c = 0.0;
printf("toprightx = %d bottomrightx = %d toprighty = %d bottomrighty = %d\n",
toprightx, bottomrightx, toprighty, bottomrighty);
// find m and c for symmetry line
if (toprightx == bottomrightx) {
m = (-toprighty + bottomrig... |
Note that toprightx, bottomrightx, toprighty, bottomrighty have been
declared as integers further up in the code.
There's your answer. Calculations that involve only integers are performed in integer math, including divisions. It doesn't matter that the result is then assigned to a float.
To fix this, either declar... |
6,727,007 | 6,867,899 | Using inline to Insert a header content | The content of a header file needs to be copied and paste onto a few of my classes. Reason been - using include directive does not make reference of the file available to an external compiler, therefore it looks like my only option been to copy the content of the header into my classes.
I was wondering if I can use spe... | The most likely cause of your external compiler not expanding the includefile when compiling is a failure to setup the include search path -- however addressing the specific question, you can get the gcc compiler to expand all the include files using the -E option.
So,
gcc -E mycfile.c >myexpeandedcfile.c
should wo... |
6,727,087 | 6,727,196 | C++ Virtual function being hidden | I'm having a problem with C++ inheritance.
I have a class hierarchy:
class A {
public:
virtual void onFoo() {}
virtual void onFoo(int i) {}
};
class B : public A {
public:
virtual void onFoo(int i) {}
};
class C : public B {
};
int main() {
C* c = new C();
c->onFoo(); //Compile error - doesn't exi... | The issue that you are experiencing is related to how name lookup works in C++. In particular, when resolving a member, the compiler will look into the static type of the object on which the member is being accessed. If the identifier is found in that class, then lookup completes and (in the case of member functions) o... |
6,727,119 | 6,727,140 | Debug assertion failure when using std::vector in a static library function called from a global object | I am currently in the middle of a code cleanup of my solution, which consists of a static library and two applications that depend on it. As a part of this code cleanup, I've been converting all of my loops over std::vectors to use iterators rather than indices. Everything was going well, until I converted a function (... | The C++ standard does not guarentee that bars's constructor will be called before that of foo. This is sometimes called the 'static initialization order fiasco'; you may get lucky in eg VS2008, but that doesn't mean the problem goes away. The page linked suggests a few potential solutions to this problem, one of which ... |
6,727,248 | 6,727,295 | SDL program can be run by itself, but not through commandline | Is this normal, or is there something weird with my program?: i wrote a small, simple program with sdl for some basic graphics. it compiles and runs. when i click on the .exe file, it runs. however, when i drag the .exe into cmd (windows 7 x64), it runs and quickly exits. the window opened through SDL shows for a momen... | When you drag your program to cmd.exe probably execution directory is changing, so your program is not finding SDL.dll and/or its data files (like images, sounds, etc).
|
6,727,383 | 6,727,398 | dynamically allocated memory after program termination | When a C/C++ program containing the dynamically allocated memory(using malloc/new) without free/delete calls is terminated, what happens to that dynamically allocated memory?
Does the operating system takes back the memory or does that memory becomes unaccessible to other programs?
| I don't think that there are any guarantees in the language standard, but modern operating systems which support sparse virtual memory and memory protection (such as MacOS X, Linux, all recent version of Windows, and all currently manufactured phone handsets) automatically clean up after badly-behaved processes (when t... |
6,727,412 | 6,742,194 | Inconsistency between std::string and string literals | I have discovered a disturbing inconsistency between std::string and string literals in C++0x:
#include <iostream>
#include <string>
int main()
{
int i = 0;
for (auto e : "hello")
++i;
std::cout << "Number of elements: " << i << '\n';
i = 0;
for (auto e : std::string("hello"))
++i;... | The inconsistency can be resolved using another tool in C++0x's toolbox: user-defined literals. Using an appropriately-defined user-defined literal:
std::string operator""s(const char* p, size_t n)
{
return string(p, n);
}
We'll be able to write:
int i = 0;
for (auto e : "hello"s)
++i;
std::... |
6,727,518 | 6,727,528 | Can't get "\a" to output a beep sound | I'm on another person's Mac-book Pro and I'm trying to output the alarm sound in C++ by outputting "\a" with cout. For some reason it's not making any sound when it outputs. Does anyone know why this could be happening? I'm using Eclipse.
| Eclipse's shell likely isn't wired up to interpret the classic BELL character correctly.
I can confirm that the bell does operate on Terminal.app however.
Note that the bell character is not part of C++ - it is purely a side effect of the console/terminal in use.
|
6,727,561 | 6,756,734 | Deleting a bitmap resource in Visual C++ | I am trying to delete a resource bitmap through code and am having trouble doing it. Went through several hours of headbanging with google. Here is the code:
int result;
HANDLE h;
h = BeginUpdateResource(L"C:\\Users\\Steve\\Desktop\\stub.exe", FALSE);
result = UpdateResource(h, RT_BITMAP, MAKEINTRESOURCE(IDB_BITMAP2),... | Ok, I figured out what went wrong. First off, I used the "GetLastError()" command to help widdle down the possibilities. It gave me an error 0x57 which means ERROR_INVALID_PARAMETER.
When I experimented more, it seems that in the language paramters, I listed "MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)" instead of "MAKE... |
6,727,709 | 6,727,734 | Platform independant ways of hiding console when program runs | Im looking for a way to hide the console (in windows) in my program, and ive found this code:
#if defined (__WIN32__)
#include <windows.h>
HWND hWnd = GetConsoleWindow();
ShowWindow(hWnd, SW_HIDE);
#endif
however, codeblocks keeps on giving me error: expected constructor, destructor, or type conversion bef... | In general, console applications shouldn't mess with their window. If you need more advanced stuff (show/hide your window, decide its size, ...) you should probably switch to a GUI application. This holds true even if you just don't want any window: create a GUI application and don't create windows.
On Mac and Linux no... |
6,727,796 | 6,727,888 | Using threads with MinGW? | I am building a small tool that will need to open a thread, and let the thread do its thing, no matter what happens on that thread I don't want it to interfere with the main app, just execute, handle errors and close.
How can I do this with mingw compiler? On linux I can use POSIX, but this tool will run only on win, b... | You can use pthreads-win32. It implements most of pthreads functionality using Windows threading API.
To find this, I searched Google for "pthreads mingw" and it was the first result.
|
6,728,364 | 6,728,372 | how to declare variable before you know what data type it is? | I'm new to c++ coming from a python background.
If I want input from a user and then I want to check what data type the input is (e.g. integer or float), how is it possible for me to declare the variable that I want to assign the user's input to?
| Short answer: You can't.
Long answer: You can't. C++ is a statically typed language, meaning that you have to define the type at compile time. Python is dynamically typed, so the type of an object can change from line to line.
If you want to get some input from the user though, you can just use a string though.
For exa... |
6,728,428 | 6,728,817 | Eclipse CDT Code Completion Issue | For some reason the code completion for the Eclipse CDT I'm running (in Ubuntu linux) isn't working properly. Every time I include a library nothing pops up. Is there any reason why this could be?
| Including a header in your source code is not enough. You need to tell the indexer where to look for the header. To do so, you need to go to your project's properties, navigate to the C/C++ General > Paths and Symbols item. In the Includes tab, add the folder containing your headers for the GNU C++ language. You may al... |
6,728,506 | 6,728,562 | Memory usage of WinCE Application | Is it possible to determine the memory usage of a WIN CE application? The Wince device does not support ActiveSync
| Debugging on CE5.0 device without Activesync
Debugging CE Apps without ActiveSync
Round up of Power Toys for .NET Compact Framework 3.5: Spelunking in the .NET Compact Framework
|
6,728,527 | 7,747,288 | Boost force directed layout problem | I am newbie in boost library, I tried to apply force directed layout from the boost documentation website but I encountered the error like this when I try to compile my code:
error: no matching function for call to ‘random_graph_layout(MyGraph&, CoordSqMap&, double, double, double, double, boost::minstd_rand&)’
error:... | If you are using a relatively new version but not the latest release, there was a bug in some versions where the interfaces to the functions had been updated but the documentation hadn't been. The correct documentation is at http://www.boost.org/doc/libs/1_47_0/libs/graph/doc/fruchterman_reingold.html (and the other c... |
6,728,536 | 6,728,547 | What would be a better way to check if a number is prime? |
Possible Duplicate:
Checking if an int is prime more efficiently
bool isPrime(int num)
{
for(int i = 2; i <= (num/2)+1; i++)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
I've looked on Wikipedia, but I don't understand any of the fast primality tests it d... | For one thing, you only need to iterate while i * i <= num.
After that, you might notice that testing whether a number is a multiple of 2 is just a bit test. Once you know the number isn't even, you know there are no even factors, so you can skip testing them.
That leads to:
bool isPrime(int num)
{
if (num < 4) re... |
6,728,571 | 6,728,632 | Memory leak or memory error when trying to handle nested objects/structs & dynamic arrays. Possible Xcode/malloc issue | When I compile with Xcode and run this, I get the error, at least 100 times in a row, malloc: *** error for object 0x100180: double free, with the debugger pointing to line C. Strangely, In the code I distilled this from, the exact same error occurs, but the debugger points to the equivalent of line B. I tried but coul... | The problem is a_struct doesn't have proper copy constructor and operator =. Due to this at a time two a_struct::dynamic_array are pointing to the same memory location and both will be calling delete[] dynamic_array; in the destructor. Hence, double delete.
Always, remember that whenever you have a row pointer inside a... |
6,728,627 | 6,728,803 | Finite State Machine For Embeded Devices | I have made several menus using FSM's but with a VERY clunky interface. I took a year long break from programming to facilitate a relocation and just tonight re-wrote my old FSM code.
It can be seen HERE
The problem with my code is it requires heavy rework of the StateMachine class and the event processor whenever you ... | If you're writing your own class - consider implementing a generic FSM, and then fill it with states and events.
Basically it would be a simple interface with something like this as methods:
create();
addState(someState, stateFunction);
addEdge(someStateOrig, someStateDest, event);
processEvent(event);
start(startFromS... |
6,728,631 | 6,728,664 | Delete pointer object in C++ | I read the following code for deleting pointer object in the open source project X3C.
//! Delete pointer object.
/*!
\ingroup _GROUP_UTILFUNC
\param p pointer object created using 'new'.
*/
template<class T>
void SafeDelete(T*& p)
{
if (p != NULL)
delete p;
p = NULL;
*(&p) = NULL;
}
But I ... | It's completely pointless. Under ordinary conditions, the unary * and & operators are inverses of each other (with a few details, like that the expression &*foo is not an lvalue even if foo is an lvalue), although operator overloading can change that behavior.
However, since T* is always a pointer type regardless of t... |
6,728,782 | 6,730,400 | How does GetModuleHandle work in Visual c++ | I am new to c++ and this code always returns NULL even though i know the file exists:
HMODULE hModule = GetModuleHandle(TEXT("C:\\Users\\Steve\\Desktop\\stub.exe"));
Interestingly, if i copy stub.exe to C:\Windows\system32, it finds the module with this code:
HMODULE hModule = GetModuleHandle(TEXT("stub.exe"));
Am i ... | You can only call GetModuleHandle(L"C:\\Users\\Steve\\Desktop\\stub.exe"); when you're running C:\Users\Steve\Desktop\stub.exe.
But in general, you don't call GetModuleHandle for your EXE name. Since there's only one EXE per process, you just call GetModuleHandle(0).
|
6,728,805 | 6,728,875 | Is this use of the "," operator considered bad form? | I have made a list class as a means of replacing variadic functions in my program used for initializing objects that need to contain a changing list of elements. The list class has a usage syntax that I really like. However I haven't seen it used before, so I was wondering if I shouldn't use it just because of that fac... | Why not overload the << operator as QList does? Then use it like:
playlist.queue << song1 << song2; // The queue now contains song1 and song2
playlist.queue << song1 << song3 << song4; //The queue now contains two song1s and song2-4
|
6,728,986 | 6,758,575 | Database access in parallel threads , viable option? | I have the following situation
main()
{
hnd = CreateTHread( func1 );
// Call fun2()
wait(hnd);
return ;
}
fun2()
{
//Access database to perform some read operation on TAble A
}
func1()
{
//Access database to perform some read operation on TAble A
// Recursive operations
}
What I observed is, fu... | A similar question - Multi-threaded database read access
Oracle JDBC interfaces as well as Oracle native drivers (i suppose) are capable of handling multithreaded requests ( http://www.cs.umbc.edu/portal/help/oracle8/java.815/a64685/tips1.htm )
However when it comes to implementation in the database engine - this is ... |
6,729,214 | 6,729,253 | rand() returns same values when called within a single function | I'm a C++ newbie and I'm stumped on this. I need to call this function in my main function three times but each time it gives me the same result, i.e. pull_1, pull_2, pull_3 are the same. What do I need to do to make them actually random?
string PullOne()
{
string pick;
string choices[3] = {"BAR", "7", "cherr... | You shouldn't call srand() before each call to rand(). Call it once – somewhere at the start of your program.
The problem is you restart the random generator so it starts to produce the very same pseudorandom sequence from the very same point.
|
6,729,428 | 6,729,466 | Cannot open include file: 'vector.h': No such file or directory | At the top of the file, I have:
#include "vector.h"
then I do a:
vector<vtarg> targVector;
and got the following error
Cannot open include file: 'vector.h': No such file or directory
Am I missing out something? I tried #include "vector" even more errors.
#include "afxwin.h"
#include "vector.h"
// CTargDlg dialog
cla... | You need to use
#include <vector>
instead, without the .h file extension. Furthermore, the vector template lives in the std namespace, so you should define your vector like
std::vector<vtarg> targVector;
Also make sure to include whatever headers are necessary for vtarg.
|
6,729,542 | 6,729,593 | One if else statement will not execute | Below is the section I am having trouble with
if(transition == *(vec.end()-1)) { //vec contains the ASCI code
vec.pop_back();
--vec_index;
result.append(vec[vec_index]);
} else if(colors.find(modified.substr(1)) == colors.end()) {
cout << result << endl;
... | transition = colors[modified.substr(1)];
will create an entry in map<> color; if it's not existing and value initialize it. That's why your else if condition will never be true. Use map::find instead of operator [] to find the entry. Something like,
map<string,string>::const_iterator it = colors.find(modified.substr(1... |
6,729,626 | 6,731,033 | Eclipse CDT: how to enable project debugging | I want to enable integrated debugging with gdb for my project in Eclipse CDT. The problem is I can't run the debugger with just a simple command like gdb myapp, because application starts using various scripts, there are lot of environment variables to set before starts, so there is shell scripts that starts applicatio... | Your run.sh could handle command line parameters. Add a parameter to it, e.g. --debug, and have it invoke GDB after it has set up whatever environment variables are required, e.g. replace
export FOO=...
... other setup ...
exec /path/to/binary $ARGS
with
... setup ...
exec $GDB /path/to/binary $ARGS
where $GDB is emp... |
6,729,690 | 6,729,730 | C++ - class method's won't to export from dll (VS - win) | I've created example C++ project in Visual Studio of dll type. It contains header file SqlLtDb.h:
using namespace std;
// This class is exported from the SqlLtDb.dll
class CSqlLtDb {
public:
CSqlLtDb(char *fileName);
~CSqlLtDb();
// TODO: add your methods here.
bool SQLLTDB_... | You need to export the class in the DLL with __declspec(dllexport), and import it in the linking code with __declspec(dllimport). Example:
class SQLLTDB_API CSqlLtDb {
...
};
You don't need SQLLTDB_API for each member, only the class - the linker will generate exports for each method for you.
|
6,730,136 | 6,730,220 | Map - finding nearest value? | I am trying find nearest RGB value in QMap (I know it probably should be HSV, but that is not the problem). Here is what I got so far:
it = images_map.find(current_rgb);
if(it != images_map.begin()){
mi = images_map.lowerBound(current_rgb).value();
}
else{
mi = i... | Possibly because .value() tries to de-reference a non-existing item?
This looks like your own custom map implementation (or wrapper), but your logic appears to be incorrect
You call lowerBound every time - except if the item you are looking for is the first in the map
If it is the first in the map, you do a search aga... |
6,730,250 | 6,730,270 | Check that current file is doc, docx, xls, xlsx or pdf format | How i can check that current file is doc, docx, xls, xlsx or pdf format? What's a c++ library i can use for this goal in my C++ application?
| If you want to understand file's type based on its contents, you can check the file's binary signature.
If you want just to check the extension, you have 2 nice options:
Use std::string functions find, find_first_of, find_last_of and substr to write your own logic that analyzes the file name.
Use boost filesystem li... |
6,730,266 | 6,730,849 | why for_each works without std:: prefix | What i think is that for_each is defined in standard namespace, but this code actually compiles and runs with the following compiler flags. Can somebody please explain why?
//@filename myprog.cpp
//g++-4.5 --std=c++0x myprog.cpp
#include<iostream>
#include<algorithm>
int main()
{
std::vector<int> v{1... | Converting comment to answer, the reason this works is ADL (Argument Dependent Lookup). Basically what this means is that on failing to find a suitable match for for_each in the current namespace, the compiler has a built-in rule which says, now look in other namespaces - and the set of namespaces it uses for this are ... |
6,730,297 | 6,730,312 | Crashing after catching exception | Why does this crash after catching std::bad_exception ? (I'm using VC7)
#include "stdafx.h"
#include <exception>
int validateInt (int x) throw (int,std::bad_exception) {
if ( 0 == x ) {
throw std::bad_exception("x");
}
return x;
}
class C {
int i;
public:
C(int);
};
C::C(int i... | Because you cannot stop exceptions from leaving the constructor initialization list. After you catch it, it's rethrown automatically. (It then crashes because you have an unhanded exception.)
This is a good thing: if your members cannot be properly initialized, your class cannot properly exist.
|
6,730,403 | 6,730,431 | How to delete object constructed via placement new operator? | char * buf = new char[sizeof(T)];
new (buf) T;
T * t = (T *)buf;
//code...
//here I should destruct *t but as it is argument of template and can be
//instantiated via basic types as well (say int) so such code
/*t->~T();*/
//is incorrect (maybe correct? Strange, but it works on VS 2005 for basic types.)
//and this cod... |
...instantiated via basic types as well (say int) so such code
t->~T(); is incorrect...
Wrong. That code is legal and correct in template code even if T can be a primitive type.
C++ standard: 5.4.2
5.2.4 Pseudo destructor call [expr.pseudo]
The use of a
pseudo-destructor-name after a dot . or arrow -> operato... |
6,730,422 | 6,731,138 | Boost.Chrono vs. Boost.Date_Time | With Boost version 1.47, the Chrono library was introduced. Is Boost.Chrono meant as a replacement for Boost.Date_Time?
If not, what are the differences between them and when should I use which?
When should I consider replacing Boost.Date_Time by Boost.Chrono in an existing project?
| From Boost.Chrono's documentation:
Boost.Chrono aims to implement the new time facilities in C++0x, as proposed in N2661 - A Foundation to Sleep On. That document provides background and motivation for key design decisions and is the source of a good deal of information in this documentation.
More specifically, Boost... |
6,730,540 | 6,730,845 | QXmlStreamWriter and cyrillic | I have a problem with encoding when writing XML files via QXmlStreamWriter in windows, how can I resolve it? Using stream.setCodec("UTF-8") or "windows-1251" is not helped.
QFile *file = new QFile(filename);
if (file->open(QIODevice::WriteOnly | QIODevice::Text))
{
QXmlStreamWriter stream(file);
... | Most likely the interpretation of the string literals in your source file is the problem, not the configuration of the stream writer.
Make sure your source file is encoded in UTF-8 and use QString::fromUtf8("Imja") etc. (Imja in cyrillic of course) instead of the implicit literal to QString conversion.
|
6,730,607 | 6,730,827 | How to get the exception reported to boost::future? | If I use Boost futures, and the future reports true to has_exception(), is there any way to retrieve that exception? For example, here is the following code:
int do_something() {
...
throw some_exception();
...
}
...
boost::packaged_task task(do_something);
boost::unique_future<int> fi=task.get_future()... | According to http://groups.google.com/group/boost-list/browse_thread/thread/1340bf8190eec9d9?fwc=2, you need to do this instead:
#include <boost/throw_exception.hpp>
int do_something() {
...
BOOST_THROW_EXCEPTION(some_exception());
...
}
...
try
{
boost::packaged_task task(do_something);
boost::uniq... |
6,730,664 | 6,730,704 | Why doesn't C++ make the structure tighter? | For example, I have a class,
class naive {
public:
char a;
long long b;
char c;
int d;
};
and according to my testing program, a to d are built one after another, like
a-------
bbbbbbbb
c---dddd
- means unused.
Why does not C++ make it tighter, like
ac--dddd
bbbbbbbb
| Class and struct members are required by the standard to be stored in memory in the same order in which they are declared. So in your example, it wouldn't be possible for d to appear before b.
Also, most architectures prefer that multi-byte types are aligned on 4- or 8-byte boundaries. So all the compiler can do is lea... |
6,730,820 | 6,731,032 | in include if i use "test.h" is the same with "path/test.h"? | I am working in ubuntu under c++ language.
I have a question: i use #include"header.h". Is this the same with /path/header.h? I ask you this question because as I've seen is not the same thing. Need some explications.
I ask you this question because I've downloaded and install gsoap on my computer. I added all the nec... | If header.h is in the directory path/, then #include "header.h" will work for those header and source files (which #include header.h which happen to be in the same directory as header.h (path/).
On the other hand, if you are #include-ing header.h in a file that is in a different directory than path/, then the above w... |
6,730,914 | 7,702,921 | C++/WIN32 (XP) Bluetooth device name change | Does anyone know how to change the Bluetooth device name programatically?
Or where is the device name stored?
| Resolved
Here is the ready-to-go solution encapsulated into a class method.
bool CBluetooth::ChangeLocalRadioName(LPTSTR newName)
{
LPTSTR instanceID = GetGenericBluetoothAdapterInstanceID();
if (instanceID == NULL)
{
//_tprintf(_TEXT("Failed to get Generic Bluetooth Adapter InstanceID\n"));... |
6,730,943 | 6,731,456 | Logical error: Unable to determine the cause of segmentation fault | for (i = (routeVector.size () - 1); i >= 0; i--)
{
cout << "Connected to -> " << routeVector[i].exitPoint;
for (j = (routeVector.size () - 1); j >= 0; j--)
{
if (routeVector[i].selectedBranchesVector.size() > 0)
{
cout << "\n: routeVector[i].select... | This is dependent on the type of i and j - if i and j are unsigned, the above loops will loop back around quite happily - which is probably what is going on - print the indexes and you'll see...
|
6,730,969 | 6,731,080 | Decimal or Float (SQL Server and C++) | What is the best way to store 17 decimals (ex. 1.12345678901234567) in a column table in SQL server?
Also which type should I use in C++ to be able to push these 17 decimals into the SQL Query?
Thanks
| You actually seem to have 18 digits there (including the integer part). You would need a 128 bit float to store this, see: http://en.wikipedia.org/wiki/Quadruple_precision_floating-point_format (80 bits would work too, if you have access to such a CPU. See: http://en.wikipedia.org/wiki/Extended_precision)
To read and s... |
6,731,027 | 6,731,889 | boost::unique_lock vs boost::lock_guard | I don't well understand the difference betweeen these two lock classes.
In boost documentation it is said, boost::unique_lock doesn't realize lock automatically.
Does it mean that the main difference between unique_lock and lock_guard is that with unique_lock we must call explicitly the lock() function ?
| First to answer your question. No you don't need to call lock on a unique_lock. See below:
The unique_lock is only a lock class with more features. In most cases the lock_guard will do what you want and will be sufficient.
The unique_lock has more features to offer to you. E.g a timed wait if you need a timeout or if... |
6,731,111 | 6,731,979 | Knowing the number of template parameters in the declaration | If I have,
template<typename T1, typename T2, int N>
class X {};
Is there any way, that I can know class X has 3 template arguments ?
Use case in brief: There are two library classes ptr<T> (for normal pointer) and ptr_arr<T,N> (for pointer to array). These two are interacting with another class in following way:
temp... | There is no standard way to do this (unless you use variadic sizeof(Args...) in C++0x) but that's beside the point -- the question is wrong.
Use overload resolution.
template <typename T>
void clear (ptr<T> & obj) {
destroy (obj);
}
template <typename T, int N>
void clear (ptr_arr<T,N> & obj) {
destroy_arr (ob... |
6,731,204 | 6,735,855 | Violation access in time compilation (0xC0000005) | The process I want to do is to make the FFT to an image (stored in “imagen”) , and then, multiply it with a filter ‘H’, after that, the inverse FFT will be done also.
The code is shown below:
int ancho;
int alto;
ancho=ui.imageframe->imagereader->GetBufferedRegion().GetSize()[0]; //ancho=widht of the image
alto=ui.... | This part of the code
H_cast = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*M*N);
H_cast= reinterpret_cast<fftw_complex*> (H); // casting from double* to fftw_complex*
first allocates a new buffer for H_cast and then immediately sets it to point to the original H instead. It doesn't copy the data, just the pointer... |
6,731,331 | 6,731,484 | Is it still safe to delete nullptr in c++0x? | In c++03 it is pretty clear that deleting a null pointer has no effect. Indeed, it is explicitly stated in §5.3.5/2 that:
In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.
However, in the current draft for c++0x this sentence seems to be missing. In the rest... | 5.3.5/7 says:
If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will call a deallocation function (3.7.4.2). Otherwise, it is unspecified whether the deallocation function will be called.
And 3.7.4.2/3 says:
The value of the first argument supplied to a deallocatio... |
6,731,551 | 6,731,614 | Difference between . and :: in C++ for static members? |
Possible Duplicate:
When do I use a dot, arrow, or double colon to refer to members of a class in C++?
When I try to access my static variable using Class.Variable I get the error that Error left of 'Variable' must have class/struct/union and when I do Class::Variable I get no error. Although in both cases I get Va... | Static members of a class can be accessed through two ways
(a) With instances of class - Use . e.g. obj.variable
(b) Without instance of class - Use :: e.g. class::variable
|
6,731,782 | 6,732,812 | undefined reference to a class ERROR | I am working in c++ /ubuntu.
I have:
libr.hpp
#ifndef LIBR
#define LIBR
#include <string>
using namespace std;
class name
{
public:
name();
~name();
std::string my_name;
std::string method (std::string s);
};
#endif
and
libr.cpp
#include <iostream>
#include <string>
#include <stdlib.h>
#i... | What are the steps you're using to compile your "project"?
I performed the following steps and managed to build it with warnings/errors.
g++ -Wall -c libr.cpp
ar -cvq libr.a libr.o
g++ -Wall -o libr main.cpp libr.a
One last thing, if I change the order off the last command, like
g++ -Wall -o libr libr.a main.cpp
I ... |
6,731,874 | 6,731,910 | How to see all header files included by a cpp file in VS 2008 |
Possible Duplicate:
Displaying the #include hierarchy for a C++ file in Visual Studio
I have a cpp file that includes multi-level header files (nested), and so difficult for me to know exactly what final header files are included. It apparently includes one header file, but I want to know where is that header file a... | You can add the /showIncludes switch to the compiler. Then it will list all includes for the cpp files.
More info can be found here.
|
6,732,068 | 6,732,094 | QUdpSocket. How to get the sender's ip address? | I have a server program that uses QUdpSocket.
How do I find the ip address of the sender?
| From http://doc.qt.io/archives/4.6/qudpsocket.html#readDatagram,
qint64 QUdpSocket::readDatagram ( char * data, qint64 maxSize, QHostAddress * address = 0, quint16 * port = 0 )
You pass the addresses of a QHostAddress and a quint16 to the receive function, which get populated with the desired data.
|
6,732,127 | 6,734,796 | Is there a way to enforce specific endianness for a C or C++ struct? | I've seen a few questions and answers regarding to the endianness of structs, but they were about detecting the endianness of a system, or converting data between the two different endianness.
What I would like to now, however, if there is a way to enforce specific endianness of a given struct. Are there some good comp... | The way I usually handle this is like so:
#include <arpa/inet.h> // for ntohs() etc.
#include <stdint.h>
class be_uint16_t {
public:
be_uint16_t() : be_val_(0) {
}
// Transparently cast from uint16_t
be_uint16_t(const uint16_t &val) : be_val_(htons(val)) {
}
// Transpare... |
6,732,177 | 6,732,211 | Destructor not being called when leaving scope | I am learning memory management in C++ and I don't get the why only some of the destructors are called when leaving scope. In the code below, only obj1 destructor is called when myfunc ends, not for the dynamically allocated obj2.
int myfunc (cl1 *oarg) {
cout << "myfunc called" << std::endl;
cl1 obj1(222,"... | If you allocate a object using new
obj2= new cl1;
Then unless you call delete on it, its destructor won't be called implicitly.
EDIT: As @David, meantions in comments, One may call destructor of an object explicitly but in my experience there is rarely a need to manually call the destructor unless one is using placeme... |
6,732,238 | 6,732,293 | c++ use thread as timer | I have my project with a different thread that make some stuff.
It's all ok, but I wish have some function called each 20ms (for example), but considering the time spent to the function... I try to explain better... I call the function, and the function spent 6ms to exit, so I wish that the thread sleeps 14ms (20 - 6),... | What about this:
clock_t start, end;
while( true )
{
start = clock();
myFunction( );
end = clock();
Sleep(20-(end-start)*CLOCKS_PER_SEC/1000.0);
}
|
6,732,320 | 6,732,358 | Is initialization of a memory block with NULL values equivalent with free? | Suppose I have a pointer *p which pointer to 10 memory blocks on the heap. Now, instead of free() it, I clear it manually with NULL (or '\0') like this:
for (int i = 0; i < length; ++i{
p[i] = '\0';
}
Is this considered a memory block is freed when every bit is cleared to zero? Or, I have to use free() to tell th... | The OS has data structures in the heap that keeps track of what's allocated and where. Using malloc and free updates these structures, you cannot do it manually. You are leaking memory if you just zero the memory contents.
|
6,732,583 | 6,743,268 | "QObject::startTimer: timers cannot be started from another thread" without timers && CPU consumption | I created a multithreaded application in Qt (4.7.2). Only the main thread has an event loop.
The issue is that sometimes I get the following warning in the console:
QObject::startTimer: timers cannot be started from another thread
After this happens, the app consumes 100% of CPU (I have a single core CPU). It seems, ... | Thanks, to @vrince I've fixed the problem. I used signals/slots mechanism + Qt::QueuedConnection to communicate with GUI
For example, if I need to set text of QLabel from worker thread, I can make in my worker thread signal
void textChanged(QString);
then I connect this signal to the slot of QLabel using Qt::QueuedCo... |
6,732,706 | 6,732,743 | c++ passing arguments by reference and pointer | in c++
class bar
{
int i;
char b;
float d;
};
void foo ( bar arg );
void foo ( bar &arg );
void foo ( bar *arg );
this is a sample class/struct and functions
i have some Qs
what's the difference between 1st and 2nd way of passing the argument in 'asm', size, speed ?
how the arguments are passed to ... | The pointer and the reference methods should be quite comparable (both in speed, memory usage and generated code).
Passing a class directly forces the compiler to duplicate memory and put a copy of the bar object on the stack. What's worse, in C++ there are all sort of nasty bits (the default copy constructor and whatn... |
6,732,711 | 6,732,806 | how to write and call a function without object \ when we dont want to call with an object | i am using different classes and also objects relavent to those different classes. Now, i want to write a seperate function which use to joint two vector to another vector. where should i write these type of seperate functions. Can i use a new header file for that? actually, i made a new header file (ConnectedSegment.h... | These free functions can be in the header (will need to be declared inline as Pedro highlights in his comment) - or they can be declared in the header and defined in an implementation file - for example,
#header
vector<int>& join_int_vector(vector<int> const& lhs, vector<int> const& rhs);
# cpp
vector<int>& join_int... |
6,733,033 | 6,733,129 | How to specialize a complex template with inheritance - C++ | I can't seem to find the right syntax to specialize this template :
template <class Object, class Var, class Invert, class Step = Var, unsigned int FIXED = IW_GEOM_POINT>
class TSin : public BasicTween<Object, Var> {...
I want to keep <Object> as a template parameter but specialize all other parameters. I am trying it... | The error is you're redefining class TSin. I don't think you can do that.
What you can do is declare the generic template and specialize the definitions of the class:
template <class Object, class Var, class Invert, class Step = Var,
unsigned int FIXED = IW_GEOM_POINT>
class TSin;
template <class Object>
c... |
6,733,093 | 6,733,204 | Performance/priority in Boost thread with accept() (Linux) | I have implemented a C++ class which launches a separate thread accepting connections (with boost::asio). The whole class is intended to be an asynchronous "command receiver" for a bigger program.
The main trouble is: when waiting for incoming connections, the thread is substantially idle. My perception is that this is... | if you or the class you use is doing an accept call, then the thread is blocked and is waiting for the OS to do some things. SO the thread is (should) not be consuming any CPU ressources, if it does so, it is either
within the system call (nothing you could change) or
there is a time-out and the thread is looping to... |
6,733,177 | 6,733,436 | Image processing Basics | I am planning to do a project on Image Processing, my knowledge in this subject in general is low. My Preferred Language is C++.
Can the members out here give me:
A Brief idea of What Image Processing is?
What books should i consult [ please keep in mind i am a beginner and am ONLY interested in making a college Proje... | I would suggest reading a good book. Image processing is not a programming field - it's an engineering field and it involves mathematics and signal processing knowledge and intuition. The Gonzalez and Woods Image Processing is quite good and doesn't require a vast knowledge of signal processing before you start reading... |
6,733,236 | 6,733,475 | how to use gsoap without installing it in ubuntu? | i am working in c++ under ubuntu. is there a way for using gsoap without installing it?
I did install it. i've copied all the gsoap dependencies....and now i would like to delete it and try to see if it's working.
what is your opinion?
THX. Appreciate
| gSoap is a compile-time tool, there's no runtime stuff to leave installed. From the moment you compiled the C++ side wrappers into library or exe, you only need to ship the files that wrap access to the target language (Python, java, whatever you chose).
You can safely uninstall gsoap and test.
|
6,733,334 | 6,733,401 | empty a specific element of a vector | I want to set an element at a specific position of a vector to null, so can do it as the following:
vector<IXMLDOMNodePtr> vec1;// filled somehow
vec1[i] = nullptr;// some specific position i
ps. I want to keep the entry that is nulled, which acts like a place holder, so I think maybe vec[i] = 0 will do?
| May be erase() will help, e.g.
vec1.erase(vec1.begin() + i);
When you iterate through next, that entry will not be there...
Now that we know what you want to do, something like this ought to work..
vector<boost::optional<IXMLDOMNodePtr> > vec1;
// populate
// to erase
vec1[i] = boost::none; // now effectively null.
T... |
6,733,431 | 6,733,614 | c++ compile error in debug but not in release | I'm trying to compile a small COM dll (using visual studio 2008 pro), and it compiles fine in release, but when I try to compile it in debug I get a compilation error:
error C2664: 'bool (MyClass &, double)': cannot convert parameter 2
from 'MyClass' to 'double'.
Now this error comes from a line in the code where I... | The error message suggests you're using MSVC. It's library implementation contains debug checks on predicates. In particular, for a partial order predicate (such as your less), I think it tests whether Pred(a,b) && Pred(b,a) == false. Obviously that won't work here.
(One of the common errors with predicates is that peo... |
6,733,471 | 6,733,565 | Check for zero or a denormalized number in c++ | I currently have some code where I have to normalize a vector of doubles (divide each element by the sum). When debugging, I see sometimes that the elements in the vector are all 0.0. If I then take the sum of the elements, I get either 0.0 or 4.322644347104e-314#DEN (which I recently found out was a denormalized numbe... | #include <limits>
#include <cmath>
double epsilon = std::numeric_limits<double>::min();
if (std::abs(sum) < epsilon) {
// Don't divide by sum.
}
else {
// Scale vector components by sum.
}
Addendum
Since you are trying to normalize a vector, I would venture that your sum is the sum of the squares of the vector ele... |
6,733,509 | 6,733,664 | boost interprocess mutex vs boost thread mutex | I'm just realized that it seems to have two mutex 'world' in Boost. definition of some mutex under boost::interprocess and mutex under boost::thread.. could both be use interchangeably ? for exemple scoped_lock with boost::wait ?
| As far as I know you can use interprocess mutex instead of boost::thread mutex , but take into account they'll be probably slower as they are intended to run in interprocess memory.
You cannot use the synchronization mechanisms from thread and use them in interprocess, these are not at all designed for multi-process sy... |
6,733,586 | 6,739,551 | Setting edge properties before creating the graph | I'm generating a boost::graph, with some 300k edges. I create the set of edges in a loop, in which I also calculate some properties of the edges. Since I need all edges to create the graph, I don't have access to the edge_descriptors yet. Is there a way to do this without doing another pass over the entire set again? W... | If you know the number of vertices(then you can initialize a graph and then you can add edges later).I have no idea how'd you make the graph if you do not know the number of vertices beforehand.
if you have vertices(i.e. if you make vertex_descriptors as soon as you get a value - for vertex) then you can add edges to ... |
6,733,683 | 6,733,735 | Why must C++ constructor use dynamic allocation for array? | In my course notes these two examples are given. Apparently the first one is not allowed, is there a technical reason why I can't allocate on stack? Or is this the C++ standard?
// Constructor may force dynamic allocation when initializating an array of objects.
Complex ac[10]; // complex array init... | The first one is not valid syntax. But assuming your Complex class has a public copy-assignment operator (the implicit one should probably be fine), then the following should be fine:
Complex ac[10]; // complex array initialized to 0.0
for ( int i = 0; i < 10; i += 1 ) {
ac[i] = Complex( i, 2.0 );
}
|
6,733,821 | 6,734,236 | Reading the RSP register from Microsoft C++ | Since inline assembler is not available in Microsoft C++ when compiling for the x64 architecture, I can't figure out how to access the RSP register (stack pointer). I know I can read it using RtlCaptureContext, but this would also perform a lot of unwanted operations. Also it would be a few thousand times slower (for m... | You can get it indirectly using the _AddressOfReturnAddress() (see MSDN reference) intrinsic.
Obviously, you do not get to know for sure where the current stack frame stops, but you can guesstimate it with whatever stack variables you have and by looking at the generated assembly.
In combination with Olipro's suggestio... |
6,734,224 | 6,734,405 | C++ class template specialization question | By looking at the following code, I am confused by line 3.
Line 3 is not a special case of the base template, it is more like a "class overload". But it can be compiled successfully.
The obj1 in line 7 is defined according to line 3, but failed to compile.
How come?
template<typename S,int T, void(* U)()> class Bar{}; ... | As long as that form is not used anywhere - then the compiler will not complain. If it is used, and the compiler has to instantiate - then it will complain. Which is why if you uncomment, you get the error - at this point, the compiler sees the flawed partial specialization.
|
6,734,275 | 6,734,313 | What is the difference between -1 and ~0 | The title really says it all: what is the difference between minus one and tilda (ones-complement) zero?
The question came up during a discussion of the best way to specify a bit mask in which all bits are set. Which of the following is better?
int func(int value, int mask = -1) {
return (value & mask);
}
or
int f... | The first variant relies on 2's complement representation of negative numbers, which isn't necessarily used. 1's complement can be used too... or other encoding. My vote is for the second approach
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.