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 |
|---|---|---|---|---|
4,378,017 | 4,378,052 | Why can't I assign an array to another? | I can't seem to wrap my head around the reason the following code won't compile.
In my header file I declared an array as a static class member:
class foo {
private:
#define SIZE 50
static char array[SIZE];
// further code goes here
}
In the implementation, I have to initialize the array.
char foo::array[SIZE] = new[]... |
There's no such thing as new [] . You need to remove the [].
Because ::operator new returns a pointer, not an array. Pointers are not arrays, and trying to treat the two interchangeably will result in pain. Just because arrays will decay into pointers doesn't mean that arrays are pointers.
foo::array[SIZE] is already ... |
4,378,054 | 4,380,414 | Why the this-pointer address is something else than expected in the destructor (c++) | I have a weird problem with a this-pointer in a base-class destructor.
Problem description:
I have 3 classes: A1, A2, A3
A2 inherits publicly from A1 and inherits privately from A3
class A2:private A3, public A1 {...}
A3 has a function getPrimaryInstance() ...that returns an A1-type reference to
an A2 instance:
A1& A3... | You use of C casts is killing you.
It is especially liable to break in situations with multiple inheritance.
You need to use dynamic_cast<> to cast down a class hierarchy. Though you can use static_cast<> to move up (as I have done) but sometimes I think it is clearer to use dynamic_cast<> to move in both directions.
A... |
4,378,149 | 4,378,258 | What's a lightweight shared memory-based IPC mechanism in C/C++ for Windows? | I've been working on a few C++ projects now which involve doing some simple IPC using window messages. In a number of cases, some extra data is passed with the window messages by putting the data into a shared memory segment and then passing the pointer into the shared memory with the SendMessage call. Re-doing this al... | Although does not meet all of your criteria, ZeroMQ (http://www.zeromq.org/) might be worth looking at. It is small, simple and fast. Also it gives you message passing semantics which may help depending on the type of applications you are using
|
4,378,219 | 4,378,256 | Function Implementation in Separate File | What is the correct syntax for having function implementation in a separate file? For example:
foo.h
int Multiply(const int Number);
foo.cpp
#include "foo.h"
int Multiply(const int Number)
{
return Number * 2;
}
I see this used a lot, but when I try it I get an error having to do with a missing main() function.... | Roughly speaking, you need to have a main() function inside one of your C++ files you are compiling.
As the compiler says, you just need to have a main() method inside your foo.cpp, like so:
#include "foo.h"
#include <iostream>
using namespace std;
int Multiply(const int Number)
{
return Number * 2;
}
int main(... |
4,378,385 | 4,379,625 | Can I delete a HBITMAP object created in another process? | I'm creating a utility program which draws some (user customizable) icons onto other windows on the desktop using a global hook. As bitmap objects are specific to a process, I'm creating separate HBITMAP objects for these icons in each process before I draw them, and all these handles are stored in a shared segment in ... | Definitely you have to delete them from a process that created them - even if it works for you, for different windows version it might not.
|
4,378,411 | 4,378,517 | How to use char * in C | I have main function like this:
void main()
{
char *s;
inputString(s);
printf("%s",s);
}
and inputString function:
void inputString(char *&s)
{
//Some code line to input a string and set s point to this string
}
Is there have a function auto malloc memory enough store string which inputed (I nee... | You're mixing C and C++ in your example.
In your case before you can use s it should be initialized. For example, like this:
void inputString(char *&s)
{
s = strdup(xxx); // or malloc, calloc, etc.
}
But really, then it's better to just use plain old C:
char* inputString(void)
{
char* s = strdup(xxx);
ret... |
4,378,431 | 4,380,345 | Where can I find static Xerces 3.0.0 lib for AIX | I got the binaries from the xerces apache site but they only have dynamic lib.
I am wondering why they do not include static version of the lib?
And is there a place to get static Xerces 3.0.0 for AIX.
And its C version of it
Thanks for any input
P.S. Other then building it myself I am aware of this option but I want s... | Just as you mention in your postscript, download from Apache's site and then run the configure script:
./configure --enable-static
|
4,378,460 | 4,379,555 | Getting all the pressed keys everywhere | So is there possible to intersect all keys pressed everywhere, where everywhere is at any application? More or so like a keylogger. I was wondering if that is possible in C++ or C#.
Regards
| If you want to use winapi thaen function you are looking for is SetWindowsHookEx with flag WH_KEYBOARD. If you want to get really all kes you might use low-lewel flag instead WH_KEYBOARD_LL, but this will not translate keystrokes, so it's more difficult to work with.
I never used this flag, but i know that some flags n... |
4,378,568 | 4,379,029 | C++ : Mixing : boost::any + typeid + pointer : clone 'generic' value if it is a pointer | Here is what I would like to do:
From a boost::any I would like to know it is a pointer type.
If it is a pointer, I have to clone it
Something like this :
boost::any value= new vector<string>();
if (typeid(value).IsPointerType())
{
boost::any newValue = Clone(value);
}
Do you think that it is possible ?
Thanks fo... | You can use the type_info interface:
#include <boost/any.hpp>
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
boost::any intVal = 5;
int* a = new int(6);
boost::any ptrVal = a;
cout << intVal.type().__is_pointer_p() <<endl;
cout << ptrVal.type().__is_pointer_p() << endl... |
4,378,724 | 4,378,754 | C++ type conversion from a variable to a reference | When doing a type conversion from a variable to a reference, like:
float f = 1.0f;
int a = (int&) f;
std::cout << a;
Why do I get the actual bit-representation of the float value (and not the numeric value).
| Your code is undefined behavior, technically speaking. Your C-style cast does a reinterpret_cast which isn't defined for convering a float lvalue to int&. Maybe you just wanted to cast to an int?
|
4,378,785 | 4,378,821 | Temporary Object confusion | Have a look at this code snippet
struct S{ int i; int j;};
int main()
{
assert(S().i == S().j) // is it guaranteed ?
}
Why?
|
is it guaranteed ?
Yes it is guaranteed. The values of S().i and S().j would be 0. () implies value initialization. (that means i and j would be zero-initialized because S is a class without a user defined default constructor)
|
4,379,239 | 4,379,370 | C++ fprintf over many functions to a single text file | I am having difficulty in printing to a text file from chosen locations within a large C++ code project.
Using C++ I am using a function X which is called multiple times.
This is called from a function Y
I wish to output the results of function X to a single text file and have done so by continously using declarations... | Whatever you do. it will probably be logically equivalent to declaring a global variable. But you can ease the pain of this in various ways:
If X is a class member, you can declare the variable as a static member of X's class.
If X belongs to a namespace, your global variable can belong to that namespace.
You can decla... |
4,379,337 | 4,379,612 | C++ Initialization of static variables (Once again) | If I have two static variables in different compilation units, then their initialization order is not defined. This lesson is well learned.
The question I have: are all the static variables already allocated, when the first one is being initialized. In other words:
static A global_a; // in compilation unit 1
static B g... | Yes, the standard allows this.
There are a number of paragraphs in section [basic.life] which start out
Before the lifetime of an object has
started but after the storage which
the object will occupy has been
allocated or, after the lifetime of an
object has ended and before the
storage which the object occu... |
4,379,394 | 4,379,436 | automatic/static memory allocation | Maybe a naive question, but...
Confirm or deny:
The existence of memory for objects/variables of automatic and static storage duration is determined compile-time and there is absolutely zero chance that the program will fail runtime because there wasn't enough memory for an automatic object.
Naturally, when the const... | Two words : Stack Overflow. :P
|
4,379,518 | 4,379,766 | String gets junk on end after conversion to c_str() | This is a homework assignment, just for all that want to know.
I'm writing a vocabulary translator (english -> german and vice versa) and am supposed to save everything the user does to file. Simple enough.
This is the code:
std::string file_name(user_name + ".reg");
std::ifstream file(file_name.c_str(), std::ios::bina... | I would do this:
std::string strBuffer(length, '\0');
myread(file, &strBuffer[read], length); // guranteed to read length bytes from file into buffer
Avoid the need for an intermediate buffer completely.
|
4,379,696 | 4,379,735 | returning LPCWSTR from a function? | In order to pass an integer value to SetWindowTextW(), (I am using a unicode build, in C++, with Visual Studio 2010), would this function suffice return an LPCWSTR? I'm pretty sure there is something I am not understanding here, because it returns a strange value. I know that an LPCWSTR is a null terminated long pointe... | There is nothing wrong in itself with returning an LPCWSTR from a function. The general problem that arises though is the memory management around the return value. A LPCWSTR is typically held in allocated memory so ownership of that memory needs to be understood between the caller and callee.
I don't want to pick ... |
4,379,868 | 4,379,916 | How to remove buffer created in such way? | So I create buffer like
unsigned char *pb_buffer;
I fill it with some ffmpeg data from some older din buffer
int len = url_close_dyn_buf(pFormatContext -> pb, (unsigned char **)(&pb_buffer));
I do some stuff with that data
Now I want to delete that buffer of mine. ow to do such thing?
I tried free(&pb_buffer); ... | unsigned char *pb_buffer doesn't create a buffer, it creates a pointer, which initially isn't pointing to anything. It's the call to url_close_dyn_buf that allocates the buffer, and stores a pointer to it in the place specified by its second argument.
The documentation for url_close_dyn_buf should tell you how to free ... |
4,380,127 | 4,380,166 | error LNK2019 - Virtual destructor in abstract class |
Possible Duplicate:
Pure virtual destructor in C++
I have two classes: the abstract "Game" class and the derived "TestGame" class. All of the functions in TestGame are implemented separately to nothing (for the sake of getting it to compile). I am only getting one error:
TestGame.obj : error LNK2019:
unresolved... | You actually need to define the destructor for the base class even though it is pure virtual, since it will be called when the derived class is destroyed.
virtual ~Game() { /* Empty implementation */ }
The = 0 for pure virtual is not necessary, since you have other pure virtual functions to make your class abstract.
|
4,380,153 | 4,380,301 | Detect OS text size on win7 | I would like to detect (via c++) what the user has chosen for text size, i.e.:
Smaller - 100%
Medium - 125%
Larger - 150%
Seems like an easy one, just can't seem to find the answer....
thanks,
A
| This changes the DPI for the DISPLAY device. Use GetDeviceCaps(), LOGPIXELSX/Y. Use CreateIC(L"DISPLAY", 0, 0, 0) to create the DC. The percentage value corresponds to 96, 120 and 144 dots-per-inch.
|
4,380,189 | 4,380,288 | Reading from the Console using the While Statement | In the code below, cin only extracts non-blank characters, so I can easily work out the number of input characters, upper case, etc... that is enetered by the user, easily ignoring the blanks.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main( int argc, char** a... | Until you get the EOF character.
If you std input is comming from the keyboard:
On Windows hit ctrl^Z
On Unix hit ctrl^D
If the OS is redirecting a file to the standard input then it will happen at the end of the file normally.
|
4,380,324 | 4,380,580 | Having a function that returns int how can I run it in a separate thread using boost? | I know it looks not necessary but I hope that it would help me find memory leak.
So having a function inside a class that returns int, how can I call it from another function of that class (call it so that function that returns int would run in another thread)?
| The operating system will not reclaim memory leaks in worker threads. That's not how it works.
Fix your bugs. The world doesn't need any more crappy software.
|
4,380,329 | 8,698,591 | Integers to Matrix (cvMat) | Hey guys,
I'm working on a project. I need to use the function cvFindHomography in openCV before this step I have applied LK optical flow function, so I get the features in the first frame and in the second frame as INTEGERS, well in cvFindHomography I need to use these features but as cvMat not as integers.
Do you h... | You can use the cvMat() constructor:
CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL))
|
4,380,575 | 4,380,645 | How to launch console application using CreateProcess with Minimized main window | I have a native c++ windows application that is launching two child processes using the following code -
if (!CreateProcess(NULL, // No module name (use command line)
cmdLine, // szCmdline, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
false, // Set handl... | You need to specify in the STARTUPINFO structure that you want your console window to be initially minimized:
ZeroMemory(&si);
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_MINIMIZE;
|
4,380,608 | 4,382,480 | C++ as a high-level language? | I learned C++ for the first time years ago by reading Stroustrup's "The C++ Programming Language" for two times and participating for a year in quite a big project (though the level of c++ team was quite low). The C++ from the Founder's book was really a huge extension of good old C. Powerfull and object-oriented and e... |
So, what C++ do YOU use in you practice? Do you mix the styles, say, arrays and vectors? Are there any rules or best practices here?...
Modern C++, definitely. But in my opinion, that doesn't exactly rule out arrays. There are still cases where arrays are preferable to vectors. But when I do use arrays, I use them in... |
4,380,655 | 4,380,720 | Casting a character array into an integer | EDIT: The wrong type of num2 has been corrected.
Hello,
I have some character arrays of known size which contains raw integer data read from a binary file.
The size of all these arrays have the size of a integer.
I would like to ask whether the following operation is safe and accurate in ALL normal situation, assuming ... | It is technically safe, but there are a few things I would consider:
Add compile-time asserts to verify the sizes. Are you SURE that your char array equals sizeof(your_int_type)? Your num2 is a great example of why this is important - your typo would cause undefined behavior.
Consider the alignment. Are you sure that ... |
4,380,685 | 4,383,768 | Gtk: send focus to a toplevel window without losing the first toplevel window | Here is the situation:
1) I have two toplevel windows, A and B
2) A is in front of B
How can I send to keyboard focus to the window B while keeping the window A in front of B ?
| I'm assuming you control both windows, and this is on an X11 system like Linux. If not, it's much more challenging. I've done things like this within a single app, and here are some recollections.
You've probably figured out you can't just use gtk_widget_grab_focus() to do it. That only works for determining which widg... |
4,380,788 | 4,380,927 | FFmpeg potential mem leak like behavior points. Are there such? | So I mean like it tries to educate it self and collects some data... Are there any such points/feilds in encoding part of ffmpeg (that I hope can be disabeld)?
BTW: My problem is simple: I looked thrue out all my code. It seriosly looks like it is some part of my ffmpeg windows build leaks memory a littel... all the ti... | FFmpeg libraries use a very object-oriented design. All memory allocated should be kept track of in the context structures and freed when the relevant context is destroyed. There may be some one-time allocation and initialization of constant global data which one could call a "leak", but I believe that was all replaced... |
4,380,874 | 4,382,236 | Erase-remove idiom for deleting in a nested container? (deleting outer ones; C++ STL) | when i'm deleting from a non-nested container like a vector, i'm doing something like:
struct is_to_remove
{
is_to_remove(dynamic_bitset<>& x) : x(x) {}
const bool operator()(unsigned int id)
{
return x[id];
}
private:
dynamic_bitset<> x;
};
inline static void remove_elements_in_vector(vec... | It doesn't matter which elements are in the vector. If you define which of them should be removed, they will be removed.
As you said, the question is how to identify an element in a vector. The most obvious answer is by its index [0; vector_size - 1].
Thanks to a vector, you can easily get an element index, by the elem... |
4,380,981 | 4,381,168 | Testing Classes that Use Collaborators with Templated Methods | I like the things that templates methods can do for me, since they can be used to dramatically simplify some code I'd otherwise have to write over and over.
However, I have a very hard time testing any classes that depend on collaborators that have public template methods. The real problem is they can't be virtual, so ... | Google mock framework provides a way to create a mock with template parameters. Then you have to add a templated base class and pass a mock object to the constructor of the class under test.
|
4,381,050 | 4,381,097 | How to convert a String into Unsigned Long. With a twist | Hello
I have a string parser who receives as its input a hex number:
For Example:
String X="0x120005f38"
As you can see the number is in HEX, how do I convert this to unsigned long?
If this was decimal based string I could use the string to unsigned long function.
I am guessing there are a couple of steps, and I am no... | Use strtoul:
strtoul("0x120005f3", 0, 0);
strtoul reference on cplusplus.com. See how that works on Codepad.
EDIT: Changed to strtoul, did not notice that unsigned long is required.
|
4,381,095 | 20,255,265 | What if the system time changes while I'm doing timed_wait with a duration? | When using timed_wait on a boost::condition_variable with a duration, will the wait condition time out after the duration even if the user (or ntp) changes the system time?
E.g.,
boost::posix_time::time_duration wait_duration(0, 0, 1, 0); // 1 sec
// ** System time jumps back 15 minutes here. **
if( !signal.timed_wait... | As of the date of writing (Nov 2013), if the wall-clock time changes while you're waiting on a boost condition variable, you simply will get bad results.
If you don't have to use boost, you can use what is called the "monotonic clock." Since the monotonic clock is unaffected by wall-clock time changes, it is not vulne... |
4,381,281 | 4,381,615 | CURLpp: TLS Handshake Error | This question is similar to another one, concerning pyCURL
I have the following error when I send a post request to a secure url, using CURLpp https://stackoverflow.com/questions/1942719/pycurl-tls-handshake-error
Ok, so according to the answer to the previous question, I should use libcurl with openSSL. If I run curl ... | cURLpp is just a wrapper over libcURL, it doesn't dictate which SSL implementation libcURL uses.
Am not exactly sure how you've come to the when I switch to CURLpp, it uses gnuTLS, instead of openSSL conclusion but I suspect that you have multiple libcurl.so installed, the one curl uses and another that your app is usi... |
4,381,518 | 4,381,590 | About owner and owned window in windows | How can i get all windows owned by a window? (not it's child)
| You can use EnumWindows to get the list of windows and then, for each window handle, call GetWindow with GW_OWNER flag to get the owner. In this way you can get the list of owned windows for a specified window handle.
That's true. A parent window is not the same than the owner window.
|
4,381,632 | 4,381,689 | Loading a DLL that calls functions in the DLL that loaded it | I have a DLL that will be loaded by a program, and that DLL will in turn load another DLL to handle some stuff that ought not to be in the main DLL. However, the second DLL needs to be able to talk to the first DLL. Is it possible for a DLL to use exported functions in the DLL that loaded it? For instance
Program load... | Yes, it will work. DLL B can safely call LoadLibrary on DLL A to get the instance handle for the GetProcAddress call the function it needs. The module loader will figure out that DLL A is already in the process memory and will just return an instance handle for it to DLL B.
Note: there are specific caveats with version... |
4,381,780 | 4,381,905 | Using long and arrays in C++ | I've been working on a program that converts numbers into binary. As you can see my program here, I've written so that it can scale for larger numbers then a traditional binary code, such as 2 lines (16-bits) for numbers bigger then 255. However, going larger requires long instead of int, but that doesn't seem to be pl... | You are making your code far more complicated than it needs to be. This will print out a single 32-bit integer in binary:
const unsigned int bit_count = sizeof(int) * 8 - 1;
int a;
std::cin >> a;
for (unsigned int i = bit_count; i > 0; --i)
{
unsigned int t = (1 << i);
std::cout << (a & t ? "1" : "0");
}
std... |
4,381,841 | 4,381,885 | Qt - How to intercept the application's close event (if there's one) | I need to do some work right before my application closes (note that I said my application and not it's main window). Is there an application close event or any other way to accomplish this?
The reason that I can't rely on the main window's close event is that my application runs on the background leaving a system tra... | Your application is likely derived from QApplication. You could put your cleanup code in the destructor of your application:
class MyApp: public QApplication {
public:
~MyApp() {
// cleanup code here
}
};
Or, in your main(), you probably have something like this:
int main(int argc, char *argv[]) {
... |
4,382,008 | 4,382,857 | Using boost::format in a boost::lambda | For some reason, I fail to use boost::format in a boost::lambda. Here is a (hopefully) compilable simplification of my code :
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <boost/assign/list_of.hpp>
#include <boost/format.hpp>
#include <boost/lambda/lambda.hpp>
namespace bl = boost::lambda;
in... | For some reason, your code evaluates boost::format("%10d") % bl::_1 immediately, rather than on each invocation of the lambda.
To prevent this, you need to wrap boost::format("%10d") in a call to bl::var, just as you have done with std::cout.
Unfortunately, doing this requires Boost.Lambda to deduce the return type of ... |
4,382,440 | 4,382,461 | C++ operator+ and operator+= overloading | I'm implementing my own matrix class in c++ to help me develop my understanding of the language. I read somewhere that if you've got a working += operator, to use it in your + operator. So that's what I've got:
template <class T>
const Matrix<T>& Matrix<T>::operator+(const Matrix<T> &R){
Matrix<T> copy(*this);
... | operator+() should not return a reference type as it is a new (locally declared) instance that holds the result of the operation.
|
4,382,656 | 4,382,696 | Why is std::map::operator[] so counter-intuitive? | It seems to me 'evil' (in the C++ FAQ sense of the word), for an operator which is generally used to access a data structure to suddenly be defined to insert data into a data structure.
I guess the issue is 'what would be better'? This question is answered easily for certain types of mapped value; for example, if we m... | The basic problem is that there is no syntactic way to reliably distinguish:
dosomething(collection[foo]);
from
collection[foo] = something;
in the operator's definition. Because it may appear in either location, the class makes sure that it can handle both, providing a default to overwrite, if necessary. If you... |
4,382,844 | 4,385,391 | Is there an easy way to sort a CObList? | I am pretty new to MFC and C++ applications, so I apologize if my question is too trivial. Anyway my boss has some legacy code written in VC++ and there is a list of objects stored in a CObList that I need to sort. I need to sort this list based on some integer value stored in that object. Is there an easy way to do th... | You probably know this already: if you are new to C++, please don’t use the MFC collection classes (CObList, CArray etc.). Instead, use the STL (std::vector, std::list etc.). The Product Manager for Visual C++ said as much here (look for the post by RonaldLaeremans).
But sometimes you have legacy code and you have to u... |
4,382,942 | 4,392,946 | Deleting element from one set by calling erase(iterator) on another set. Is this normal behavior? | I found out that an element from one set can be deleted from another set by using the erase method that accepts an iterator. I can't explain why this happens, and I would like to know if this is normal behavior or not.
So, lets set the scene:
I have a set of objects that I separated in two STL sets, for logical reasons... | This might work because of how your vendor happens to implement std::set<T> and std::set<T>::iterator, but it's not guaranteed to.
Standard section 23.1.2 Paragraph 7 and Table 69 say that the expression a.erase(q) is valid when a is an object of an associative container class type (set is an associative container) and... |
4,383,015 | 4,383,047 | Why does assignment operator call constructor? | I am just playing around to understand smart pointers and trying to make mine but I come across a situation that I do not fully understand. Here is the code:
#include <iostream>
template <class T>
class Holder
{
private:
T * obj;
public:
Holder(T * tt) : obj(tt)
{
std::cout << "... | holder = b attempts to assign from b to Holder. b is of type A*, and holder is of type Holder<A>.
The Holder template defines assignment from another instance of the same Holder type, so the compiler looks for a conversion from A* to Holder<A>. It finds the constructor, and uses that.
Constructors which may take exactl... |
4,383,398 | 4,383,459 | c++ unit testing using Boost | I am really new to Unit testing, and I have the following really basic program:
#include "stdafx.h"
// classes example
#include <iostream>
using namespace std;
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
bool isEq ();
};
void CRectangle::set_values (int... | The simplest way to test it is to do something like this (I'm not attempting to write great test cases, I'll leave that to you):
#define BOOST_TEST_MODULE isEq Test
#include <boost/test/included/unit_test.hpp>
#include "CRectangle.h"
BOOST_AUTO_TEST_CASE(isEq_test)
{
CRectangle rect;
rect.set_values(5,5);
... |
4,383,602 | 4,391,500 | How to force inclusion of "unused" object definitions in a library | My question is similar to these but doesn't seem to correlate exactly:
How to force inclusion of an object file in a static library when linking into executable?
Forcing symbol export with MSVC
What I've got is something like so:
struct thingy;
struct container
{
static container& instance(); // singleton
int regi... | Well, the other answers where good attempts but ultimately fruitless. I am going to use the refit trick but the rest appears to have been a red herring; it kind of makes sense since the template in question isn't actually used anywhere else so the fact that it's not explicitly instantiated shouldn't make a difference.... |
4,383,766 | 4,383,776 | Why does const_cast need to state what you're casting to? | According to the standard (§5.2.11) a const_cast casts away cv-qualifiers (const or volatile).
Here's a simple example. First you declare two functions taking a pointer and a reference:
class Bar { ... };
void foo_ptr(Bar*);
void foo_ref(Bar&);
then you create a reference-to-const:
Bar b;
const Bar& cb = b;
and then ... | const_cast can be used to add or remove const and volatile qualifiers. So, if such a syntax were allowed, all of the following would be legitimate target types of const_cast<>(&cb):
Bar* (1)
const Bar* (2)
volatile Bar* (3)
const volatile Bar* (4)
You intend (1). (2) is usually sill... |
4,383,805 | 4,383,934 | Is it possible to have an array of different objects that come from the same base class? | I'm trying to design a weapons class for a game. This is some of the code I have come up with to fit my needs:
class weapon {
public:
int fireRate;
int bulletDamage;
int range;
ofImage sprite;
ofImage bulletSprite;
bullet bullets[50];
int activeBullet;
public:
void fire();
};
class machineGun: publ... | As noted by Ross, your array has to be of type weapon* to allow you to downcast specialized weapon types.
So,
weapon* weapons[totalWeapons];
weapons[0] = new machineGun;
Also as noted, as you're creating these dynamically, you'll want to make sure that you clean them up later or you're going to run into memory leaks
|
4,383,812 | 4,384,727 | How do I accept keyboard input in a live fashion? | I am currently writing a program in c++ that is very similar to the classic "snake" program with a few changes. I am writing it so that it will update the screen five times a second, based on ctime, possibly more if it can be handled. One thing that I would like to do is make it so that the program has a variable in th... | The simplest method is to use ncurse library.
However, if you prefer "raw" linux programming, you can use select and getchar:
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
fd_set readfs;
struct timeval timeout;
int res, key;
while (1) {
/* .. do somethi... |
4,383,864 | 4,385,378 | Downloading File in Qt From URL | In my program I need to download a file, and I came across this article:
http://www.java2s.com/Code/Cpp/Qt/DownloadfromURL.htm
This code does work but it doesn't fit into my program so I re-coded it. I haven't completed it all but I've got the basics coded. However, when I test it, it pops up with a send error report ... |
You're using uninitialized pointer, so it points out to nowhere. Initialize reply with NULL in your constructor.
You should connect reply after it was created (reply = manager.get(...)), not inside of your constructor.
QNetworkReply is never deleted by QNetworkManager as docs say:
Do not delete the reply object in t... |
4,383,868 | 4,383,881 | vector iterators incompatible | I have some class where I want to use a large amount of vectors.
class Bar {
Bar ();
std::vector<Foo> * _grid;
void someFunction ();
}
Bar::Bar () {
_grid = (std::vector<Foo> *)malloc(_gridSize * sizeof(std::vector<Foo>);
memset(_grid, 0, _gridSize * sizeof(std::vector<Foo>);
}
void Bar::someFunct... | You almost certainly don't want to dynamically allocate the vector; just include it as a member of the class:
class Bar {
std::vector<Foo> _grid;
};
If you really want to dynamically allocate the vector, you want to use new, which constructs the vector. As it is written now, you malloc space for the vector and s... |
4,383,946 | 4,384,925 | conflicts: definition of wchar_t string in C++ standard and Windows implementation? |
From c++2003 2.13
A wide string literal has type “array of n const wchar_t” and has static storage duration, where n is the size of the string as defined below
The size of a wide string literal is the total number of escape sequences, universal-character-names, and other characters, plus one for the terminating L’\0’.... | The standard requires that wchar_t be large enough to hold any character in the supported character set. Based on this, I think your premise is correct -- it is wrong for VC++ to represent the single character \U000E0005 using two wchar_t units.
Characters outside the BMP are rarely used, and Windows itself internally ... |
4,384,008 | 4,384,126 | Making Stack Walker Works in Application with Optimization Enable | I am refering to article at http://www.wintoolzone.com/articles/AuthoringStackWalkerForX86.pdf
I am using VC++ 2008. I realize that when I turn the optimization to "Maximum Speed (/O2)", even I set the "Omit Frame Pointer" explicitly to No, getting function returned address will not work correctly through stack frame p... | I suppose its main assumption isn't the pattern
push ebp
mov ebp,esp
but rather the assumption that ebp is always used as frame pointer. This allows simple stack unwinding: ebp points to last saved stack frame, all data above it are locals, the next value on the stack is the return address of the call... |
4,384,021 | 4,384,069 | trying to write a recursive function that counts the number of sequences that sum up to that number C++ | Okay, so here is what I'm trying to do. The user inputs a number. I'm trying to write a recursive function that counts the number of sequences that sum up to that number (user input).
For example:
Then the number of sequences that sum up to 6 is 11 (including 6 itself).
6
5+1
4+1+1
3+1+1+1
2+1+1+1+1
1+1+1+1+1+1
2+2+1+... | Hint: try to find a function that gives the number of sequences with sum n and terms not larger than k.
EDIT:
Forgive me if this sounds harsh, but... your updated code is all wrong. It's hard to see what you intended. I can guess, but that would be pointless.
Here's what I had in mind: a sequence should be in nonincrea... |
4,384,052 | 4,384,064 | Confusion in understanding C++ standards | In C++98
12.6.2/4 : After the call to a constructor for class X has completed, if a member of X is neither specified in the constructor's mem-initializers, nor default-initialized, nor initialized during execution of the body of the constructor, the member has indeterminate value.
What does nor initialized during ex... | nor initialized during execution of the body of the constructor is not correct IMHO.
The wordings have been changed in C++03 from nor initialized (in C++98) to nor given a value
After the call to a constructor for class X has completed, if a member of X is neither specified in the constructor’s mem-ini... |
4,384,170 | 4,384,219 | C++ returned pointer points to something other than what was returned from the function | In the following code in my program (simplified of course), the output in funcA and funcB are different, meaning the pointer's value got changed somewhere along the way. I wasn't able to comfirm that the address of face changed as this error magically doesn't pop up in the debugger (QT Creator's debugger). But here's t... | First of all using raw pointers with STL containers can be dangerous.
vector<Face> faces; is local to funcB(), so after the function returns it is destroyed and are left with a dangling pointer (which was once pointing to a valid local value). Using a dangling pointer invokes Undefined Behaviour.
|
4,384,240 | 4,384,387 | How do I get a Windows Performance Counter for the current process | I am writing code for a C++ application foo.exe. Inside the application, I want to log its address space usage. So the performance counter I want to look at is "\Process(foo)\Virtual Bytes". The problem I am encountering is that there may be multiple instances of foo.exe running on the system. In perfmon, I can see ... | Your instance is the one that has the ID Process counter value that matches your current process ID. Unfortunately there is no other way than to get all instances and enumerate through them untill you find the instance that is yours, but that is fairly trivial to do.
|
4,384,262 | 4,701,314 | Does Google c++ testing allow for creation of stubs | Does Google c++ testing allow for creation of stubs either automatically or manually?
| Google Test is a unit testing framework in the XUnit style. Google Mock (http://code.google.com/p/googlemock/) is a related project that provides stubs and mocks. If you are looking for a C++ test framework that is in the BDD style you can look at Igloo (http://igloo-testing.org/).
|
4,384,277 | 4,384,334 | How to read float number with more digits in C++? | I'm having issues when I try to read a float number from a file. I need to read 3 float numbers given in a line like this:
v -30.50889491515995 -31.95820181187489 0
(I'm doing a parser from a .obj file from Rhinoceros)
Here is my code (before this I read a string to see if is a 'v'):
fstream f(name.c_str());
... ... | C++ always inputs the numbers with full precision, but you need to specify the precision for display (i.e. when outputting the values):
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
std::istringstream iss("30.50889491515995 -31.95820181187489 0");
float x, y, z;
if (iss >> x >> y... |
4,384,377 | 4,384,403 | Name lookup bug in VS2010 | I am pretty sure it is a bug in VS 2010, but it's always a good idea to check on SO
struct A{
static int s;
};
struct B{
static int s;
};
struct C : A, B{
void fn(short s){ // Ambiguous access of 's' here!!!
s = 2;
}
};
int A::s;
int B::s;
int main(){
C c;
}
VS gives- "er... | Visual C++ is worried about the diamond problem- the instance member named "s" is ambiguous due to diamond-shaped inheritance. But here, it should be shadowed by the local parameter named "s", so there's nothing illegal about this code. It should compile cleanly, unless you have something weird set in your environment ... |
4,384,406 | 4,385,423 | Placing methods in .h vs. .cpp files | I've seen code for a class placed into a separate C++, while the method definitions are placed in the header file. My 1st OOP experience is with Java, in which all the methods are placed in the class file, and I actually prefer this.
Does placing all my methods in a header file affect the assembly code generated by th... | There're a few valid reasons for header/implementation splitting and
separate compilation:
1. That may be a job requirement - for example, you're supplying a
binary library + header to somebody, or your colleagues are too conservative
to accept anything else.
2. Its still required to develop very large projects (say, >... |
4,384,414 | 4,386,718 | AltiVec vec_msum equivalent for float values | Is anybody aware of a method to achieve vec_msum functionality against a vector of float values?
I'm quite new to SIMD, and although I think I'm starting to make sense of it - there are still a few puzzles.
My end goal is to rewrite the function "convolve_altivec" (as found in the accepted answer for this question) s... | For a float version you need vec_madd.
Here's a float version of the previous 16 bit int version and test harness I posted in response to your earlier question:
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <altivec.h>
static float convolve_ref(const float *a, const float *b, in... |
4,384,518 | 4,387,433 | How to get .gcda files when the process is killed? | I have a binary build with -fprofile-arcs and -ftest-coverage. The binary is run by a process monitor which spawns the process as a child process. Then, when I want the process to exit, I have to go through the process monitor. It sends a SIGKILL to the process. I found out that .gcda files do not generate in this case... | SIGKILL is a "hard" kill signal, that cannot be caught by the application. Therefore, the app has no chance to write out the .gcda file.
I see two options:
Catch signals other than SIGKILL: any sensible process monitor should send a SIGTERM first. init and the batch managers I've encountered do this. SIGKILL is a last... |
4,384,746 | 4,385,221 | What the best or the most frequently used C++ compiler under Windows? | What the best or the most frequently used C++ compiler under Windows?
Besides Visual Studio, it seems there have two options: Dev-C++ and Eclipse.
|
Besides Visual Studio, it seems there have two options: Dev-C++ and Eclipse.
Strictly neither of your named examples are "compilers" they are all IDEs. Dev-C++ specifically used GCC, and is packaged with MinGW/GCC, Eclipse is not distributed with a compiler at all.
Visual C++ in its "Express Edition" is available fo... |
4,384,765 | 4,384,825 | What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__? | What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__, and where are they documented? How do I decide which one to use?
| __func__ is an implicitly declared identifier that expands to a character array variable containing the function name when it is used inside of a function. It was added to C in C99. From C99 §6.4.2.2/1:
The identifier __func__ is implicitly declared by the translator as if, immediately following the opening brace of... |
4,384,936 | 4,384,955 | Problem with C++ code for number theory | int sum(int number, int min, int counter)
{
int temp=0, n;
n=number+temp;
if ((number>=(n/2)) & (number!=min))
{
number --;
temp ++;
while (number>=(n/2))
{
cout << number << "+"<< temp << "\n";
number --;
temp ++;
counter +... | You have no exit criterion. Your function will just recurse into the skies.
|
4,385,155 | 4,385,263 | Setting my lib for LD_PRELOAD makes some processes produce loader errors | I get the following error when I try to run a script I have only execution access for:
uname: symbol lookup error: /home/dumindara/random/sotest/a.out: undefined symbol: dlsym
This is after I have set LD_PRELOAD environment variable to /home/dumindara/random/sotest/a.out.
a.out has a test malloc function, and calls dls... | I assume that your a.out file is a shared object and not a executable and move on...
dlsym() is a function from the libdl library, which usually resides in the libdl.so.2 shared object on modern Linux systems.
I'll hazzard a guess that your a.out shared object is not linked to libdl. That means that when you preload in... |
4,385,265 | 4,385,298 | How to get a exclusive timer ID for WM_TIMER? | I subclassed a control, the control has wm_timer itself. and i need a create a timer for my code, how can i get a exclusive timer id for my code?
| Unfortunately, you can only get SetTimer to create a new ID when the HWND is null.
If you want a unique timer, you need to use SetTimer without an HWND, in which case timer messages are posted to your timer proc directly.
To send timer messages to a subclassed window you simply have to choose a timer ID you hope is uni... |
4,385,297 | 4,385,743 | Overloading rules for User-defined-literals in c++0x | I am a little confused about overloading rules,
let's say there are following literal operators,
unsigned long long operator "" _xx(unsigned long long cooked_literal_int); //1
unsigned long long operator "" _xx(const char * raw_literal_string); // 2
unsigned long long operator "" _xx(long double cooked_literal_double);... | I believe that 13.5.8/7 clarifies this issue :
Note: literal operators and literal
operator templates are usually invoked
implicitly through user-defined
literals (2.14.8). However, except for
the constraints described above, they
are ordinary namespace-scope functions
and function templates. In particular... |
4,385,469 | 4,386,128 | Problem in defining a module in omnetpp | Hi
I'm writing a project in omnet, but I'm stuck on defining my own module. On https://github.com/lbedogni/Basic-Broadcast-Simulation there is the full code. The problem is that i get the following error message:
<!> Error in module (cCompoundModule) scenario.host[0] (id=4) at event
\#1, t=0: Class "basic::Floodin... | I am not familiar with it, but from package.ned
// designate the NED package of this folder
package basic;
// namespace of module C++ classes
@namespace(basic);
@license(LGPL);
you need to be in namespace basic I guess?
And you flooding class is not defined within namespace basic?
|
4,385,782 | 4,385,820 | Sanity check of array parameters (strlen and that like) | Couldn't find the answer by serching (maybe bad keywords), so I am creating a new question.
How do you handle parameter checking for dllexported methods with string parameters. The general rule is never trust user, but in reality? For example:
int foo(const char *bar)
{
if(!bar)
return FAIL;
???
}
Say... | You can only babysit the client so far. If they pass garbage to your function, is it your problem?
|
4,385,783 | 4,387,030 | Passing char pointer from C# to c++ function | I am stuck in c# implementation side, as I am pretty new to it. The thing is, I want to pass a 'pointer'(having memory) from c# code so that My c++ application can copy pchListSoftwares buffer to pchInstalledSoftwares. I am not able to figure out how to pass pointer from c# side.
native c++ code(MyNativeC++DLL.dll)
voi... | Try using a StringBuilder
[DllImport("MyNativeC++DLL.dll")]
private static extern int GetInstalledSoftwares(StringBuilder pchInstalledSoftwares);
static void Main(string[] args)
{
.........
.........
StringBuilder b = new StringBuilder(255);
GetInstalledSoftwares(0, b);
MessageBox.Show(b.ToStr... |
4,385,803 | 4,385,858 | About windows the painting cycle of a window | Why does windows separate the painting cycle into two message wm_paint and wm_ereasebackground, why not just one?
| This is still from the good old ways where WM_PAINT could have been too slow. It was better to have at least the background drawn. It is far less important today.
You can use the default implementation which just draws the background with the window's default background brush. Alternatively, you can just ignore it and... |
4,385,806 | 4,385,997 | Determine the loaded path for DLLs | I wish to have my application in the following structure.
Exe
|
|----- DLL\DLL.dll, DLL\common.dll
|
|----- DLL2\DLL2.dll, DLL2\common.dll
My EXE will load the DLLs through
LoadLibraryEx(_T("DLL\\DLL.dll"), 0, 0);
LoadLibraryEx(_T("DLL2\\DLL2.dll"), 0, 0);
DLL.dll and DLL2.dll project will link against common.d... |
You want to load two different DLLs with the same name (common.dll) into the same process.
That seems like a bad idea to me. Is it really necessary? Could one of them be renamed?
Ensuring the DLLs you load can find other DLLs which aren't in the search path.
(If you were not dynamically loading DLL.dll and DLL2.dll t... |
4,385,879 | 4,389,848 | How to reproduce missing Qt plugin problem on dev machine? | I'm trying to deploy my Qt application that relies heavily on SQLite database via Qt's QSQLite plugin. My program runs perfectly fine in the release build on the development machine, but fails utterly to find QSQLite plugin on any machine that has no Qt installed. My problem is similar to the one in these questions:
QT... | Get Virtual box or VMware's free edition.
Install a mimimal windows system (you don't have to activate it)
Set it so that changes aren't committed to disk
Test your installs there, testing install/dependancy issues on a dev machine is never going to work.
|
4,385,915 | 4,385,951 | realloc()/HeapRealloc() fails even though enough memory is available | My machine has 8GB of RAM and is running Windows Server 2008. malloc()/realloc() fails to allocate more memory when my application has 1.5~1.7GB already allocated. I tried switching to HeapAlloc()/HeapRealloc() instead and the same situation happens.
Is there something I am missing here? What could be causing my applic... |
What could be causing my application to be unable to allocate more memory when there is clearly available RAM?
Heap fragmentation. Allocation doesn't simply ask for memory. It asks for a contiguous piece of memory.
Of course, given the sparse data you provided (how much are you trying to re-alloc when that happens? ... |
4,386,291 | 4,386,349 | C++ program dies with std::bad_alloc, BUT valgrind reports no memory leaks | My program fails with 'std::bad_alloc' error message. The program is scalable, so I've tested on a smaller version with valgrind and there are no memory leaks.
This is an application of statistical mechanics, so I am basically making hundreds of objects, changing their internal data (in this case stl vectors of double... | Run the program under debugger so that it stops once that exception is thrown and you can observe the call stack.
Three most probable problems are:
heap fragmentation
too many objects created on heap (but still pointed to from the program)
a request for an unreasonably large block of memory
|
4,386,802 | 4,390,381 | Convert ICU UnicodeString to platform dependent char * (or std::string) | In my application I use ICU UnicodeString to store my strings. Since I use some libraries incompatible with ICU, I need to convert UnicodeString to its platform dependent representation.
Basicly what I need to do is reverse process form creating new UnicodeString object - new UnicodeString("string encoded in system loc... | You could use UnicodeString::extract() with a codepage (or a converter). Actually passing NULL for the codepage will use what ICU detected as the default codepage.
|
4,386,845 | 4,387,256 | Optimization of Point to Voxel mapping | I used a profiler to look over some code which does not yet run fast enough. It found that the following function took most of the time, and half of the time in this function was spent in floor. Now, there are two possibilities: optimizing this function or going one level above and reducing the calls to this function. ... | First rule of optimization when there is math involved: Eliminate division, square roots, and trig functions.
inverse_size = 1 / _gridIntervalSize;
....that should be done only once, not once per call.
int mx = ((int)floor(position.x * inverse_size) % _gridSize);
int my = ((int)floor(position.y * inverse_size)... |
4,387,154 | 4,387,180 | Can I declare a non-member function const in C++? | Can I declare a non-member function (global function, may be) as const in C++? I understand that the const keyword actually is applied to the implicit "this" argument passed in member functions. Also since only member functions follow the "thiscall" calling convention, can const be applied for non-member functions?
Le... | No, only a non-static member function may be const qualified.
What semantic would you expect from a const non-member function ? If you want to enforce that no parameters are modified by the function, just take them by const reference.
|
4,387,167 | 4,387,217 | Undefined symbol using template | I am getting a linker error building this code:
Exclude.h file
class IsExclude
{
public:
template<typename T>
bool operator()(const T* par);
virtual ~IsExclude() = 0;
};
IsExclude::~IsExclude() {}
class IsExcludeA : public IsExclude
{
public:
IsExcludeA(std::string toCompare) :... | In the isExclude function, you write :
if ( (*pos)->operator()(toCheck) == true )
This calls IsExclude::operator() which is declared but not defined, so the linker has a good reason to complain. It seems to me that you would like to have a polymorphic behavior on operator() but that you fell into the 'template functio... |
4,387,288 | 4,387,335 | convert std::wstring to const *char in c++ | How can I convert std::wstring to const *char in C++?
| You can convert a std::wstring to a const wchar_t * using the c_str member function :
std::wstring wStr;
const wchar_t *str = wStr.c_str();
However, a conversion to a const char * isn't natural : it requires an additional call to std::wcstombs, like for example:
#include <cstdlib>
// ...
std::wstring wStr;
const wch... |
4,387,316 | 4,387,698 | How can I assign the current process to a newly created job object? | I can't seem to use the AssignProcessToJobObject function to assign the current process to a job object handle given by CreateJobObject. This has been asked a few times already on StackOverflow, but so far none of the solutions (which usually boil down to embedding an UAC manifest) seem to work for me.
I'm using MSVC9 ... | I followed a number of discussions at one point relating to job objects and UAC manifests. The only piece of information that helped me around the same problem that you're having was that this security feature (introduced in Vista) is apparently not enforced when run from a cmd.
I assume you're launching PyCmd from the... |
4,387,500 | 4,388,169 | Deleting in a linked list | Given only a pointer to the node to be deleted , how do we delete the node in the linked list...?
| The question is too ambiguous, and is likely that way for a reason (e.g. to spawn a conversation instead of test your actual knowledge of the data structure). They are likely expecting you to ask "Is this a doubly linked list or a singly linked list?" If it is a doubly linked list, its a simple matter:
curr->prev->ne... |
4,387,560 | 4,387,638 | how to assign address to a pointer where address is store in CString object? | CString str("0x1b1be0")
void* ptr = NULL;
Now i want to assign ptr = 0x1b1be0. How do I achieve this?
| Try this:
CString str("0x1b1be0");
void* ptr = (void *)_tcstoul(str.GetBuffer(), 0, 0);
And this is in pure C:
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *s = "0x1b1be0";
void *p = (void *)strtoul(s, 0, 0);
printf("%p", p);
return 0;
}
Try it on Codepad.
Note: This version has no error ... |
4,387,707 | 4,387,730 | looking for a stand-alone, in-memory data server with sequential access | We need an in-memory data structure / DB server with following characteristics:
stand-alone server: will run on the same machine as the clients, so any kind of IPC is ok
sequential access: get next/previous key
two keys (string) per record: kind of a bi-directional map, actually
in-memory only: should have option for ... | I'd suggest Kyoto Cabinet, it has an in memory function and sequential access.
edit:
what's wrong with stl map?
|
4,387,798 | 4,387,826 | Function pointers to member functions of a parent class | I have been trying to understand function pointers in C++ so that I can successfully use them in one of my projects. I am running into a logic problem though. Say we have two classes: a parent class and a child class which inherits the parent class.
class Parent{
...other stuff
void (Parent::*ptr2func) ();
.... | A void (Parent::*)() takes an object of type Parent. The function Child::afunc requires an object of type Child. Converting the pointer to void (Parent::*)() would therefore allow for an invalid call.
Member function pointers can't really be used to implement polymorphism. The traditional way to implement polymorphism ... |
4,387,807 | 4,388,176 | C++ eclipse building error | I'm programming with Galileo on Ubuntu.
My project is compiled through the terminal fine. But for the nice features of eclipse I decided to use eclipse. So I copied and pasted everything inside an eclipse project directory. Then I refreshed the project in the project explorer and everything was found by eclipse. (EDIT... | Presumably it is a makefile project. Have you set up the Eclipse IDE to use make with the correct make arguments?
Have you set up the path for the include and lib directories that you need?
Right click on the project in the tree viewer and bring up the preferences dialog and make sure.
There is a console output tab on... |
4,387,830 | 4,388,502 | 16 bpp to 32 bpp conversion | We have a encoder library which takes 32 bpp data. We have a screen capture library which needs to support 16 bpp as well. I would like to convert a 16bpp raw data into 32bpp whenever I need to pass the new screen captures to encoder. How can it be done efficiently and are there any other alternatives ?
I dont want to... | To clarify the other answers: you need to use CreateDIBSection to create bitmaps in the formats you are interested in: 16bpp and 32bpp.
The handy thing with this function is it returns a pointer to the memory buffer with the pixel data, allowing you to easily initialize the bitmap from the one source, and extract the p... |
4,387,971 | 4,388,399 | C++ passing method pointer as template argument | I have a caller function like this:
template<typename T, void (T::*method)()>
void CallMethod(T *object){
(object->*method)(args);
}
and while this works perfectly:
void (*function)(A *) = &CallMethod<A, &A::method>;
this code does not compile with error on the second line:
void (A::*method)() = &A::method;
void ... | At this point I have ascertained that you have an API that takes a function and a pointer and you need to supply it such. I assume that you must always supply it an A* pointer?
If it is a very generic callback but must be a function (can't be a boost::function) and must be a pointer (possibly void*) then you need a fun... |
4,388,374 | 4,388,423 | One way communication between two threads through Events | I have two threads that communicate in the following way: Thread A posts a message in a message queue and Thread B processes that message. Thread A has to wait until Thread B processes the message.
Thread A
.........
post a message on the message queue
WaitForSingleObject (hEvent)
Use the message processed informatio... | You needn't call ResetEvent as long as the event is an AutoReset Event. This parameter is set in CreateEvent. I think your pseudocode is OK.
|
4,388,606 | 4,388,676 | Relationship between C and C++ | When Stroustroup was designing C++, one of his goals was that C++ were as much a superset of C as possible. I understand that this is not 100% the case, but most of good code in C is also C++ code.
But I am hearing that C99 supports many things that C++ doesn't (like VLA) and that there is even going to be C1x or C0x w... | C++ is a near superset of C89/C90. (I don't recommend writing the code with the purpose of being able to compile it as either C or C++, though.) Since then, C99 diverged. The new C++ standard (often called C++0x) will have some attempt to be more compatible, but isn't going to have such things as the C99 variable-le... |
4,388,628 | 4,388,662 | C++ Change Output From "cout" | Is it possible to change text printed with "cout"? I would like to make it show the current percentage of something without having to have a new line for each percentage. Is this possible?
| This works for me:
std::cout << "1111";
std::cout << "\r";
std::cout << "2222";
\r is a carriage return symbol. Puts the "cursor" back to the beginning of the line.
Alternatively you can use \b character. This is backspace. When printed it goes one character back.
|
4,388,777 | 4,388,890 | HttpSendRequest not waiting for PHP script to finish | I'm sending an HTTP POST request from my C++ app to a PHP script on a server. Using HttpOpenRequest/HttpSendRequest/etc. Currently it waits for the PHP script to finish executing before HttpSendRequest returns. Is there anyway to change this functionality?
I'm sending the data just before my C++ application closes, so... | You may want to ignore_user_abort() in your PHP script. Then you can close the connection from your C client after the data is sent and PHP will continue to do whatever it's supposed to do.
|
4,389,204 | 4,389,230 | boost::variant<T> to std::string | I have a boost variant of looking like this: typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
I have a need for being able to convert any of the values in this variant to a std::string, I wondered if there is some template type function I could use to do this?
Or wh... | Use boost::lexical_cast, which hides the whole stringstream thing behind a convenient wrapper. This also works with boost::posix_time, since it has a suitable operator<<.
|
4,389,634 | 4,391,516 | C++ - threaded tree, ordered traversal | I've just implemented a threaded tree in C++, and now I'm trying to cout all the elements in order.
The tree was a binary sorted tree (not balanced) before I've threaded it.
I've tried doing this:
E min = _min(root); //returns the minimum element of the tree
E max = _max(root); //returns the maximum element of the tree... | Try
Node* n = _min(root);
while (n->right) {
cout << n->val << ", ";
n = _successor(n);
}
cout << n->val << endl;
This is basically your first code (note that I assume that the tree is non-empty as do you). This also won't give you a trailing ','.
The important thing is to get your successor function correct. ... |
4,389,650 | 4,389,784 | Confusion concerning boost::shared_ptr | My question revolves around whether or not I must expose my use of the boost::shared_ptr from my interface and whether or not I should expose raw pointers or references from my interface.
Consider the case of a Person who has an Employeer. Employeer internally maintains all of its employees in a vector< shared_ptr< Pe... |
For example, are all or only some of these ok:
It depends on what you're trying to accomplish. Why does the vector hold shared_ptrs instead of just directly storing Person s by value? (And have you considered boost::ptr_vector?)
You should also consider that maybe what you really ought to hand out is a weak_ptr.
If... |
4,389,950 | 4,391,371 | How to map a C array to C#? | My question has to do with trying to call a function written in C from C#. I've looked in a header file that came with the C library to understand the functions as they exist in the C dll. Here's what I see:
C code (for a function called "LocGetLocations"):
typedef enum {
eLocNoError,
eLocInvalidCriteria,
e... | In the end, this signature works:
[DllImport(@"VertexNative\Location.dll")]
public static extern uint LocGetLocations(IntPtr findContext, [Out] IntPtr[] locations, uint numberLocations, out int status);
And I can call it like this (some refactoring needed):
IntPtr[] locations = new IntPtr[20];
int status;
// findConte... |
4,389,951 | 4,390,075 | Template specialization priorities when using pointers or references | I have a Serializer class like this:
class Serializer
{
public:
// Func 1 (default)
template <class T>
void Serialize(T* pValue)
{
SerializeInternal(reinterpret_cast<char*>(pValue), sizeof(*pValue));
}
// Func 2 (specialization)
template <>
void Serialize<Serializable>(Serializ... |
It seems like C++ doesn't recognize that the Serializable interface is inherited unless you clearly specify that
This is true. If you have some class
class SerializableClass : public Serializable
only SerializableClass, not Serializable, is considered when deducing the T parameter.
If what you need is create two fun... |
4,390,007 | 4,390,201 | In either C or C++, should I check pointer parameters against NULL/nullptr? | This question was inspired by this answer.
I've always been of the philosophy that the callee is never responsible when the caller does something stupid, like passing of invalid parameters. I have arrived at this conclusion for several reasons, but perhaps the most important one comes from this article:
Everything not... | While in general I don't see the value in detecting NULL (why NULL and not some other invalid address?) for a public API I'd probably still do it simply because many C and C++ programmers expect such behavior.
|
4,390,080 | 4,390,774 | C++ | Progresssion Path | I know the basic OOP-related topics, RTTI, Templates. Reverting back from Java' Collection Framework, I tried to find such collections in C++ and found STL, and am trying to use it in my projects (although I don't know them in and out). I searched and found recommendations for books like Accelerated C++, Effective and ... | It's a tough question, because what you really need is becoming good at what you do, and thus no authoritative list exists.
That being said...
Read Effective C++ by Meyers and C++ Coding Standards by Sutter, you're not likely to understand everything if you're a beginner, so re-read them from time to time (it's also a... |
4,390,112 | 4,390,157 | boost::shared_ptr question. Why does this work? | In experimenting with this question I created an example that I utterly do not understand. In particular, it highlights my misunderstanding of pointers, references, and the boost::shared_ptr.
int& r = *(new int(0));//gratuitous pointer leak, got to initialize it to something
{
boost::shared_ptr<int> sp(new int(100... | Because r = *sp; does not do what you think it does. It assigns to the referent, that is, to the anonymous int object you created on the heap in line 1. You cannot reseat references in C++.
Here is what the standard says about evaluating reference expressions:
If an expression initially has the type "reference to T",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.