question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
7,518,732 | 7,519,345 | Why are std::vector::data and std::string::data different? | Vector's new method data() provides a const and non-const version.
However string's data() method only provides a const version.
I think they changed the wording about std::string so that the chars are now required to be contiguous (like std::vector).
Was std::string::data just missed? Or is the a good reason to only a... | In C++98/03 there was good reason to not have a non-const data() due to the fact that string was often implemented as COW. A non-const data() would have required a copy to be made if the refcount was greater than 1. While possible, this was not seen as desirable in C++98/03.
In Oct. 2005 the committee voted in LWG 46... |
7,518,744 | 7,518,785 | Non member function can be declared multiple times while member function can only be declared once? | Non mumber function can be delcared multiple times while member function can only be declared once? Is this right ? My example seems saying yes.
But Why ?
class Base{
public:
int foo(int i);
//int foo(int i=10); //error C2535: 'void Base::foo(int)' : member function already defined or declared
};
//but it seem... | From the Standard (2003), §8.3.6/4 says,
For non-template functions, default
arguments can be added in later
declarations of a function in the same
scope.
Example from the Standard itself:
void f(int, int);
void f(int, int = 7);
The second declaration adds default value!
Also see §8.3.6/6.
And an interesting ... |
7,518,837 | 7,518,864 | While loop keeps repeating | I setup a while loop where i want to choose r or h, i dont want to use forloops but i want to use a switch why is it when i enter r or h it keeps repeating a million times the cout for that case? I cant get it to just say it once..
while (chooseMove == 'r' or 'h')
{
switch (chooseMove)
{
case 'r':
... | What you mean is while (chooseMove == 'r' or chooseMove == 'h'). What you've currently written is equivalent to ((chooseMove == 'r') or ('h')), and 'h' evaluates as true.
Maybe you were also asking for help with the input logic:
char c;
bool success = false;
while (std::in >> c)
{
switch(c) {
case 'r': /* ... *... |
7,518,954 | 7,518,992 | How do I compare two generic types in C++? | I need to determine whether an element is the same as the one I'm passing by reference.
In the function Belongs I need to compare equality between d is and an element of a stored in a dynamic list:
struct Nodo{ Dominio dominio; Rando rango; Nodo* next; };
typedef Nodo* ptrNodo;
ptrNodo pri;
template<class Dominio, ... | Whatever type argument you provide for the type parameter Dominio, you've to overload operator== for that type.
Suppose, you write this:
DicListas<A,B> obj;
obj.Belongs(A());
then you've to overload operator== for the type A as:
class A
{
public:
bool operator == (const A &a) const
{
//compare this an... |
7,519,039 | 7,521,342 | Real-time keyboard input to console (in Windows)? | I have a doubly-linked list class, where I want to add characters to the list as the user types them, or removes the last node in the list each time the user presses backspace, whilst displaying the results in console in real-time.
What functions would I use to intercept individual keyboard input, and display it in rea... | You will be surprised, but this code will do what you want:
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
|
7,519,094 | 7,520,142 | Pass array from c++ library to a C# program | I'm making a dll in c++ and I want to pass an array to a c# program. I already managed to do this with single variables and structures. Is it possible to pass an array too?
I'm asking because I know arrays are designed in a different way in those two languages and I have no idea how to 'translate' them.
In c++ I do it ... | Using C++/CLI would be the best and easier way to do this.
If your C array is say of integers, you would do it like this:
#using <System.dll> // optional here, you could also specify this in the project settings.
int _tmain(int argc, _TCHAR* argv[])
{
const int count = 10;
int* myInts = new int[count];
fo... |
7,519,215 | 7,519,264 | initializing a vector of vector<doubles> c++ | Hi I want to initialize a size 9 vector whose elements are vectors of the size, say 5. I want to initialize all the elements to the zero vector.
Is this way correct?
vector<double> z(5,0);
vector< vector<double> > diff(9, z);
OR is there a shorter way to do this?
| You could potentially do this in a single line:
vector<vector<double> > diff(9, vector<double>(5));
You might also want to consider using boost::multi_array for more efficient storage and access (it avoids double pointer indirection).
|
7,519,404 | 7,519,504 | android: Unable to access struct static data members | I'm having the next kind of error when linking the application:
undefined reference to 'MyStructure::K_VARIABLE_A
undefined reference to 'MyStructure::K_VARIABLE_B
...
The structure is defined inside "MyStructure.h" as:
struct MyStructure
{
const static int K_VARIABLE_A=1;
const static int K_VARIABLE_B=2;
...
}
How c... | The preferred way to define constant values in the scope of a class/struct is this:
struct MyStructure
{
enum
{
K_VARIABLE_A=1,
K_VARIABLE_B=2, // Note that you CAN keep the trailing comma
...
};
};
|
7,519,486 | 7,519,588 | Return value copying issue (to improve debug timing) -- What's the solution here? | The most interesting C++ question I've encountered recently goes as follows:
We determined (through profiling) that our algorithm spends a lot of time in debug mode in MS Visual Studio 2005 with functions of the following type:
MyClass f(void)
{
MyClass retval;
// some computation to populate retval
... | If your definition of g is written the same as in your code base I'm not sure how it compiled since the compiler isn't allowed to bind unnamed temporaries to non-const references. This may be a bug in VS2005.
If you make the converting constructor explicit then you can use it in your function(s) (you would have to say ... |
7,519,836 | 7,519,875 | Addition of vectors c++. Cannot understand compilation error | Hi I am have written the following function for adding 2 vectors
vector<double> add(vector<double>& v1, vector<double>& v2 )
{ /*Do quick size check on vectors before proceeding*/
vector<double> result(v1.size());
for (unsigned int i = 0; i < result.size(); ++i)
{
result[i]=v1[i]+v2[i];
}
return resul... | vector<double> add(vector<double> v1, vector<double> v2 )
From the error message, I can say with 100% certaintly that this is not the function signature in your original code.
In your original code, you must be using this:
vector<double> add(vector<double> & v1, vector<double> & v2 )
If so, then make it as:
vector<d... |
7,519,886 | 7,520,161 | how to cut Faces after detection | I have been working on a college project using OpenCV. I made a simple program which detects faces, by passing frames captured by a webcam in a function which detects faces.
On detection it draws black boxes on the faces when detected. However my project does not end here, i would like to be able to clip out those face... | For C++ version you can check this tutorial from OpenCV documentation.
In the function detectAndDisplay you can see the line
Mat faceROI = frame_gray( faces[i] );
where faceROI is clipped face and you can save it to file with imwrite function:
imwrite("face.jpg", faceROI);
|
7,520,250 | 7,521,545 | effective java builder idiom equivalent in c++? | This is a great idiom I've been using since reading Effective Java. I've been trying to find a C++ equivalent or something similar and have had little luck. The traditional builder pattern found in the GoF book isn't really applicable in my case. It's one complicated object that has a very messy constructor. Below ... | Not only can it be adapted to C++ but rather the idiom has been adapted from C++.
I think the first time I heard of this idiom was before Java came into existence. IIRC Bjarne Stroustrup mentions this in C++ 2nd Edition as an explanation of why C++ does not need Smalltalk style named parameters.
I could have my dates ... |
7,520,283 | 7,521,242 | Native C++ library - who have to release the memory and how? | This is about Android. The situation:
C++ library and java wrapper classes plus native functions (JNI) for working with C++ classes from the library. When common java code needs C++ object, it creates corresponding java wrapper object which creates C++ object through native function and remembers the pointer to the nat... | At the end of the process lifetime, all process memory (both Java and C++ heap) will be freed and reclaimed by the system. One thing is though, Android activity closing does not necessarily end the process. I'm not sure what's the process shutdown policy there.
On the other hand, relying on the garbage collection and f... |
7,520,426 | 7,520,471 | How do I write a COM dll? | To better myself I am attempting to make my dll's COM compliant, I thought I'd just need to extend/implement a few interfaces and job done but now I am at a cross roads,
1) Should I learn MIDL?
2) Should I install the ATL (I am running VC++Express)?
3) Carry on reading the C++ tutorials (http://progtutorials.tripod.com... |
I was interested in transferring native C++ to Android and Java and read that the libraries would need to expose either static 'C' style functions or implement COM.
Android is Linux based operating system... It does not support DLLs and COM.
So no you can't go via COM. You need to learn how to use JNI.
|
7,520,625 | 7,520,671 | Why is sizeof(array) different in these two cases? |
Possible Duplicate:
Sizeof array passed as parameter
Given the following code, the system I'm currently on (which seems to be 64-bit given the size of a pointer) prints:
32
4
Now, the size of an int should be 4 bytes on this system, so 8*4 = 32 makes sense. Also, I understand that the size of a pointer should also... | Arrays decay into pointers when passed into functions such that you are printing the sizeof the array pointer of int of 4 bytes in foo().
The sizeof(myarray) prints the size of the array which is 32 (num elements x size of int).
|
7,520,643 | 7,521,126 | Static array of method pointers | I'm facing an error I dont understand.
I try to create and use a static array of method pointers. The declaration in my class looks like this:
static void (Client::*packetHandler[Op::handledOpcodeMax - Op::handledOpcodeMin + 1])(QByteArray &data);
Initialization takes place in my .cpp files is like that:
void (Client:... | void (Client::*packetHandler[Op::handledOpcodeMax - Op::handledOpcodeMin + 1])(QByteArray &data); declares a global variable named packetHandler. You want to define your class variable, which needs an extra Client:: like so:
void (Client::*Client::packetHandler[Op::handledOpcodeMax - Op::handledOpcodeMin + 1])(QByteArr... |
7,521,222 | 7,522,968 | How to create a constant buffer with valid dimension | Good evening,
I'm trying to send a XMFLOAT3X3 to a constant buffer (see code below).
ZeroMemory(&constDesc, sizeof(constDesc));
constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constDesc.ByteWidth = sizeof(XMFLOAT3X3);
constDesc.Usage = D3D11_USAGE_DEFAULT;
result = m_pDevice->CreateBuffer(&constDesc,0,&m_pTexTransfo... | In your case, you can just change the ByteWidth to 48 and it will be fine. If you want to group more than one value together, you're going to need to make sure that your data is aligned to 16 byte boundaries. To do this you can just add __declspec(align(16)) before defining your structures.
__declspec(align(16))
struct... |
7,521,317 | 7,521,359 | c++: Passing const int to template function | I am using the rapidxml lib.
It defines a function to parse files in this way:
template<int Flags>
void parse(Ch *text)
The lib provides const int flags for example:
const int parse_declaration_node = 0x20;
So I created a pointer to a static int in my class:
const int * parser_mode;
And in the class constructor I as... | template<int Flags> void parse(Ch *text) ... const int * parser_mode;
Your template takes an int as a template parameter, but you are passing it an int*. The types int and int* are not the same.
Try tree->parse<rapidxml::parse_declaration_node>(file->data());
|
7,521,330 | 7,521,418 | Passing unsigned integers from C++ COM object to VB6 | I am trying to access (from a VB6 application) an unsigned 32 bit integer data type returned by the method of a C++ COM object. The part of an interface is declared like:
...
interface ICOMCanvasPixelBuffer : IUnknown
{
HRESULT GetWidth([retval][out] DWORD *pWidth);
HRESULT GetHeight([retval][out] unsigned __in... | VB6 does not have unsigned datatypes. Is the COM object yours? Just change the interface to a regular, signed int. Do you really have images with width and height over 2 billion?
If the COM object is not yours, sorry, its interface is not Automation-compliant. You can put together a proxy C++ object that would convert ... |
7,521,352 | 7,521,447 | How to make a class template argument optional? | Is there any way to make a template class argument optional?
Specifically in this example:
template <typename EVT>
class Event : public EventBase {
public:
void raise(EVT data){
someFunctionCall(data);
}
}
I want to have a version of the same template equivalent to this:
class Event : publ... | With default template argument, and template specialization :
template <typename EVT=void>
class Event : public EventBase {
public:
void raise(EVT data){
someFunctionCall(data);
}
};
template <>
class Event<void> : public EventBase {
public:
void raise(){
someFun... |
7,521,390 | 7,521,435 | Inlining an overloaded operator c++ | Can/should an overloaded operator have to be inlined to gain better efficiency (wrt time or whatever) if that operator will have to be used frequently?
I want to overload the '+' operator to add big vectors very frequently in my code. Hence the question.
| Ideally, you'd profile your code and then decide what to inline. There really isn't much of a difference between when you decide to inline regular operators, over overloaded ones.
|
7,521,494 | 7,521,521 | I get an 'identifier not found' error | This is my first attempt to create a basic list (i need this at school) and i get a strange error.
This is the script:
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
using namespace System;
using namespace System::Threading;
struct nod
{
int info;
nod *leg;
};
int n, info;
nod ... | you need to put a forward declaration to use a method before it's implementation. Put this before main :
void addToList(nod*& v, int info);
In C/C++ a method should be used only after it's declaration. To allow recursive call between different methods you can use forward declarations in order to allow the use of a fun... |
7,521,551 | 7,521,719 | C++ Boost Concepts Deprecation Warning | The top of this page warns about deprecated a API. Where can I find its replacement then?
| this code wasn't updated to newer model. here you can find all now supported functions.
|
7,521,660 | 7,521,822 | friend function of std::make_shared() in Visual Studio 2010 (not Boost) | how to make friend function of std::make_shared().
I tried:
class MyClass{
public:
friend std::shared_ptr<MyClass> std::make_shared<MyClass>();
//or
//friend std::shared_ptr<MyClass> std::make_shared();
protected:
MyClass();
};
but it does not work (i'am using Visual Studio 2010 SP1)
| How about adding a static method to your class:
class Foo
{
public:
static shared_ptr<Foo> create() { return std::shared_ptr<Foo>(new Foo); }
private:
// ...
};
Here's a little hackaround:
class Foo
{
struct HideMe { };
Foo() { };
public:
explicit Foo(HideMe) { };
static shared_ptr<Foo> create() { return s... |
7,521,805 | 7,521,873 | implicitly converting lambda to boost::function | I'm trying to make a implicit lambda convertible to lambda function by the following code:
#include <boost/function.hpp>
struct Bla {
};
struct Foo {
boost::function< void(Bla& )> f;
template <typename FnType>
Foo( FnType fn) : f(fn) {}
};
#include <iostream>
int main() {
Bla bla;
Foo f( [](Bla& v) -> { std... | You are missing a void:
Foo f( [](Bla& v) -> void { std::cout << " inside lambda " << std::endl; } );
// ^ here
Or, as @ildjarn pointed out, you can simply omit the return type:
Foo f( [](Bla& v) { std::cout << " inside lambda " << std::endl; } );
With either of these lines, your code compiles fine ... |
7,521,842 | 7,529,023 | Reading and writing files in Cyrillic in c++ | I have to first read a file in Cyrillic, then randomly pick random number of lines and write modified text to a different file. No problem with Latin letter, but I run into a problem with Cyrillic text, because I get some rubbish. So this is how I tried to do the thing.
Say, file input.txt is
ааааааа
ббббббб
ввввввв
I... | Because you saw something like ■a a a a a a a 1♦1♦1♦1♦1♦1♦1♦ 2♦2♦2♦2♦2♦2♦2♦ printed to the console, it appears that input.txt is encoded in a UTF-16 encoding, probably UTF-16 LE + BOM. You can use your original code if you change the encoding of the file to UTF-8.
The reason for using UTF-8 is that, regardless of the c... |
7,521,863 | 7,521,939 | I want to store void pointers to functions along with the type of them | I am trying to make a vector hold void pointers to functions, which will later be called secuentially.
So, lets say that I have got three functions. int a(), void b();, bool c();
My vector is vector<void *> vec;
And my function that stores pointers to functions.
void registerFunction(void *func)
{
vec.push_back(fu... | void* can't safely be used as a generic pointer-to-function type (though you might be able to get away with it).
But any function-to-pointer value can be converted to another pointer-to-function type and back again without loss of information. So you can use, for example, void (*)() (pointer to function returning void... |
7,521,969 | 7,521,977 | C++ Skipping the rest of the current `for` iteration and beginning a new one. | Consider this C++ code
for(int i=0; i<=N; ++i)
{
if(/* Some condition 1 */) {/*Blah Blah*/}
if(/* Some condition 2 */){/*Yadda Yadda*/}
}
Is there any keyword/command so that if condition 1 evaluates to true and execution of /*Blah Blah*/ I can skip the rest of the current iteration and begin a new iteration by i... | Use the keyword continue and it will 'continue' to the next iteration of the loop.
|
7,522,245 | 7,522,295 | c++ Passing *this as reference during construction of self | Is the following safe? I know, strictly speaking, dereferencing a pointer before the thing to which it points has been properly constructed seems dangerous, but I imagine the compiler will just provide a pointer without actually doing any dereferencing. Well, I assume.
(Note: gInst doesn't actually use the reference un... |
(Note: gInst doesn't actually use the reference until much later.)
Then it's completely safe. (Taking note you say "the reference", not "the value".)
Compilers will just warn about it for the reason you've stated, but there's nothing undefined about it, just "risky". Note that you can often trump compiler warnings (i... |
7,522,336 | 7,522,380 | Why does this function overloaded for three integer types fail to compile? | This attempt to define a function overloaded for three sizes of integers fails. Why?
byte hack(byte x)
{
return x+1;
}
unsigned short hack(unsigned short x)
{
return x+2;
}
unsigned int hack(unsigned int x)
{
return x+3;
}
The compiler tells me:
zzz.cpp:98: error: redefinition of ‘unsigned int hack(unsi... | Your compiler/code thinks that byte and unsigned int are the same thing...
|
7,522,346 | 7,522,498 | Right shift and signed integer | On my compiler, the following pseudo code (values replaced with binary):
sint32 word = (10000000 00000000 00000000 00000000);
word >>= 16;
produces a word with a bitfield that looks like this:
(11111111 11111111 10000000 00000000)
Can I rely on this behaviour for all platforms and C++ compilers?
| From the following link:
INT34-C. Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand
Noncompliant Code Example (Right Shift)
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed typ... |
7,522,355 | 7,677,802 | How can I create a local database inside a Microsoft Visual C++ 2010 Express project? | How can I create a local database inside a Microsoft Visual C++ 2010 Express project?
I can't find this simple answer in the web. The only answer I've found is for Visual Studio: using project > add new item > local database. But this option isn't available in Visual c++ 2010 Express edition.
I tried installing "Micros... | Ok, I got a solution at last. Regrettably I must answer my own question...
I used SQLite library (http://www.sqlite.org/). It was a little complicated because the sqlite documentation is a bit vague, but I did as follows:
Download sqlitedll*.zip - extract .def and .dll files somewhere.
Generate the lib file with a co... |
7,522,367 | 7,522,401 | Programming style from "Game Coding Complete" | I have recently read Mike McShaffry's Game Coding Complete and noticed the code style I haven't seen elsewhere yet. The more important things I noticed were the names of base classes defining interfaces starting with an I like IActor, protected member variables' names starting with m_ like m_Type and names of virtual m... | That's called Hungarian Notation. It's encoding information about the variable into the variable name.
For example, m_params means "a member variable called params". IActor means "A class called Actor intended to be used as an ifterface". It is something that is a very hot topic. Most people agree Hungarian Notation is... |
7,522,479 | 7,522,650 | How do I ensure data is written to disk before closing fstream? | The following looks sensible, but I've heard that the data could theoretically still be in a buffer rather than on the disk, even after the close() call.
#include <fstream>
int main()
{
ofstream fsi("test.txt");
fsi << "Hello World";
fsi.flush();
fsi.close();
return 0;
}
| You cannot to this with standard tools and have to rely on OS facilities.
For POSIX fsync should be what you need. As there is no way to a get C file descriptor from a standard stream you would have to resort to C streams in your whole application or just open the file for flushing do disk. Alternatively there is sync ... |
7,522,680 | 7,522,760 | Interpolating an angle counter clockwise? | Right now 'm using linear bezier to interpolate angles:
float CardAnimation::valueAt( float valueA, float valueB, float t ) const
{
return (1.0f - t) * valueA + t * valueB;
}
....
if(m_startCard.m_angle != m_endCard.m_angle)
{
m_targetCard->m_angle =
... | If abs(endAngle - startAngle) > PI, then subtract 2*PI from endAngle. Then instead of going from 0.5 to 6.0, you go from 0.5 to -0.28.
Edit:
This actually assumes 0 <= startAngle < endAngle <= 2*Pi.
If 0 <= endAngle < startAngle <= 2*Pi and startAngle - endAngle > PI, then add 2*PI to endAngle.
|
7,522,691 | 7,522,873 | try throw exception handling | I'm having a little trouble with making the following piece of code work. I cannot write a throw exception so I don't know what else could I do.
case 't': // Top of Stack
try
{
cout << "Top() -- " << sPtr->Top() << endl; //this should run if the stack is not empty.
... | You're not actually throwing anything on failure, and in the case when the stack is empty you're just running off the end of the function without returning anything. Also your final log statement is only hit when the stack is empty.
You need something more like this:
int Stack::Top() const // Returns value of top inte... |
7,522,830 | 7,522,957 | cvQueryFrame() returns NULL before end of file | I'm trying to process large AVI files (approx. 61000 frames, 505MB) with
OpenCV, using cvCaptureFromAVI() and cvQueryFrame().
However, cvQueryFrame() returns a NULL pointer before it reaches the last frame
of the avi.
long int numframe = 6000;
while (numframe < 67000)
{
frame = cvQueryFrame( capture );
... | Most probably you are experienced one of the FFMPEG integration bugs. This bugreport looks very similar to your problem.
What version of OpenCV are you using?
Any way I recommend you:
Try another version of OpenCV
Try to build OpenCV without FFMPEG. Probably OpenCV will be able to read your file with VfW or GStreamer.... |
7,522,911 | 7,523,126 | DirectX multiple DLL versions? | I see that DirectX 9 has multiple DLL versions, like
d3d9.dll
d3d9_25.dll
d3d9_42.dll
d3d9_43.dll
I'm wondering what the differences are, and how I can detect it? I have always been using GetModuleHandle("d3d9.dll");, but if an application has d3d9_43.dll, then my code will not detect that the application is using Di... | If code uses D3D9, it will always use d3d9.dll at some point. Typically this is in the import table, but it can be dynamically linked (LoadLibrary). d3d9.dll provides the init code for D3D (and COM, when needed), and exports Direct3DCreate9 to create a new IDirect3D9Object.
d3d9.dll is used regardless of version, the v... |
7,522,938 | 7,523,255 | getline() error. no instance of overloaded function matches argument list. | Hi i am trying to use getline() function by giving two arguments to it. but it is giving error as no instance of overloaded function matches argument list.
Here is my code snippet:
string equation;
cout<<"Enter the string";
getline(cin, equation);
can anyone please tell me if i am missing something.
Thanks.
| There is probably another function called getline which takes different arguments. To use the one you want, you have to
#include <iostream>
#include <string>
and either use
using namespace std;
or explicitly put std:: before string, cout, cin and getline.
|
7,522,949 | 7,523,031 | Macro that accept new object | In my code, I have:
#define EV( event ) SendEvent( new event );
EV( evFormat );
But I want to pass a created object in the EV macro, like:
CEvent *ev = new CEvent();
EV( ev );
Is this possible? Because there is no way I will modify the EV macro.
| #define EV( event ) SendEvent( new event ); // Can't be changed.
The macro enforces that each call to SendEvent should create a new dynamic object. Your problem is not just that using a macro for that is stupid and e.g. reduces the readability of your source code. It is also that the macro does not allow you to cre... |
7,523,013 | 7,523,163 | C++/CLI - URL Download to File | I'm not entirely familiar with how CLI works, but I have a general idea. I have a function that takes 2 System::String variables, and uses those to download a file from a webpage. As far as the download goes, it works fine, and the file shows up in my directory with the necessary content. However, it gives me the error... | You're using getline wrong, and possibly that's causing your error. The correct idiom is this:
std::string line;
while (std::getline(myFile, line))
{
// process `line`
}
There's no need to check myFile for openness separately.
|
7,523,243 | 7,523,770 | OpenGL- Simple 2D clipping/occlusion method? | I'm working on a relatively small 2D (top-view) game demo, using OpenGL for my graphics. It's going for a basic stealth-based angle, and as such with all my enemies I'm drawing a sight arc so the player knows where they are looking.
One of my problems so far is that when I draw this sight arc (as a filled polygon) it n... | This is essentially a shadowing problem. Here's how I'd go about it:
For each point around the edge of your arc, trace a (2D) ray from the enemy towards the point, looking for intersections with the green boxes. If the green boxes are always going to be axis-aligned, the math will be a lot easier (look for Ray-AABB int... |
7,523,440 | 7,523,671 | Getting text from QLineEdit to append to QTextEdit upon QLineEdit returnpressed() | I'm trying to write a simple Qt program which takes text inside a QLineEdit and appends it into a QTextEdit object when the return key is pressed.
Here is the code for my program:
#include <QApplication>
#include <QtGui>
#define WIDTH 640
#define HEIGHT 480
int main(int argc, char* argv[])
{
QApplication app(argc... | When you run your program, you should notice on the console the following Qt error output..
Object::connect: No such slot QTextEdit::append(lineEdit.text()) in ..
You would need to qualify the append reference in your call to connect with the QTextEdit variable name textArea.
But that's not going to help much because ... |
7,523,553 | 7,523,588 | not familiar with c++ pointer, need help | on the line *binSon[0].add(x);, it give me an error, an expression must have a class type, what do i do?
struct Rectangle
{
tName Name; //name of the rectangle
struct Rectangle *binSon[NDIR_1D]; //left and right son
int Center[NDIR_1D];
int Length[NDIR_1D];
void add(Rectangle x){
if(strc... | Your problem here really isn't quite what you think, although it can be solved as is.
The correct syntax is:
binSon[0]->add(x);
The -> operator is member-of-pointer, which handles everything for you. Typically, -> should be used with pointers and . with references or the object itself (the exceptions are in interestin... |
7,523,773 | 7,523,926 | 2^power without using math.pow and multiplication | Is there any way to use code 2^power without using math.pow or multiplication operator.
So far,
I've though of using 2 counters and additions, but my programs doesn't seem to be working. Here is my work thus far.
int counter=0; // k
int userNumber=0; // p
int power=0;
int sum=0;
cout << "Enter a non-negative number:... | pow = 1;
while(userNumber > counter){
pow = pow+pow;
counter++;
}
|
7,523,924 | 7,523,974 | initiate class with an argument in class declaration | in my object State, i'd like to have object pq. but pq needs to be initialized with a parameter. is there a way to include a class that depends on a parameter into another class?
file.h
class Pq
{
int a;
Pq(ClassB b);
};
class State
{
ClassB b2;
Pq pq(b2);
State(ClassB b3);
};
file.cc
State::State(ClassB ... | You can initialize it in the initializer list, just like you do with b2:
State::State(ClassB b3) : b2(b3), pq(b2) {}
Keep in mind that members are initialized in the order they are declared in the header file, not the order of the initializers in the initializer list.
You need to remove the attempt at initialize it in... |
7,524,023 | 7,524,273 | Need some way to store functions in a list, and then call them | This list, has to hold functions, they might be from different namespaces and even methods of instanced classes.
This list will then be iterated and all the functions and methods called. It would be nice if they could contain arguments also.
I was thinking on using a std::vector, but I suspect that I am far from correc... | Have all of your functions implement the Command Pattern.
Your list becomes a
std::list<Command>
As you iterate over the list, you invoke the Execute() method of each list item.
For example, say you have a simple Command interface called Commander:
class Commander
{
public:
virtual ~Commander;
virtual... |
7,524,119 | 7,729,055 | Get Picture Messages To C++ program | I'm currently thinking of setting up a picture message import project. Something like this:
Client Mobile Device [picture message] -> our Server Device
Server Device [picture && number -> Server Computer
However I don't know if there's a possible way to do this. I could set up a google voice account and use something l... | Ok I think this is possible. I'm not sure how it works but I'll do my best.
First you have to be notified when an SMS is received by listening to SMS_RECEIVED events. BroadcastReceiver + SMS_RECEIVED
Second, you have to read the SMS attachment as explained here: Get attachment from unread MMS messages
Does this help?
|
7,524,249 | 7,524,386 | Is it well-defined/legal to placement-new multiple times at the same address? | (Note: this question was motivated by trying to come up with preprocessor hackery to generate a no-op allocation to answer this other question:
Macro that accept new object
...so bear that in mind!)
Here's a contrived class:
class foo {
private:
int bar;
public:
foo(int bar) : bar (bar)
{ std::cout << "... | Peforming placement-new several times on the same block of memory is perfectly fine. Moreover, however strange it might sound, you are not even requred to destruct the object that already resides in that memory (if any). The standard explicitly allows that in 3.8/4
4 A program may end the lifetime of any object by reu... |
7,524,448 | 7,524,544 | Naming constants which are part of a formula | For my C++ class, the instructor said he will give a score of zero to any program submitted with magic numbers. He said, even for formulas such as calculating the area of a circle (where it is common knowledge that 3.14159 is the value of Pi, we should either use a const variable or a #define directive to represent Pi ... | All in all, I think calling the 1.0 in this formula a magic number is a little extreme. Not every literal number is necessarily a magic number. The point is to make your code readable such that the person looking at it won't have to guess why you picked that number out of thin air.
In this case, I think the solution w... |
7,524,548 | 7,532,862 | getAsyncKeyState not recognizing key input | So I decided that I wanted to write a little keylogger tonight, just to learn about getAsyncKeyState. I'm trying to get my log to write to a file but the file's contents either show up blank or throw a random memory address at me (0x28fef0 before). I've heard that getAsyncKeyState doesn't function well with Windows 7... | You're using the function incorrectly. Reading the documentation before requesting help is usually a good idea...
I'll just quote MSDN here:
If the function succeeds, the return value specifies whether the key
was pressed since the last call to GetAsyncKeyState, and whether the
key is currently up or down. If the ... |
7,524,645 | 7,524,727 | Problem implementing virtual method in derived class | Hey I was trying to multiple inherit a pure virtual function using MVS2010 Compiler. So I can run a draw for all renderable objects.
So here is the diagram
in ASCII
|Renderable | |Entity |
|virtual bool draw()=0;| | functions in here |
is - a is - a
Shape
So i... | First, you need to declare the draw function again in your Shapes class. Then make sure it has the same signature as the one declared in the Renderable class.
//Shapes.h
#ifndef H_SHAPES_
#define H_SHAPES_
#include "Renderable.h"
#include "Entity.h"
class Shapes : public Entity, public Renderable
{
public:
... |
7,524,887 | 7,524,983 | QTextStream and std out | I have the code:
QTextStream out(mFileHandle);
out << (QTime::currentTime().toString(Qt::LocalDate) + " - ").toAscii();
out << "Something another";
std::cout << "Data: \n";
std::cout << out.string();
out.flush();
It writes to file but after 'Data:' I get '0', why? How to send data to both streams?
| It looks to me like you constructed your QTextStream out from a file handle. This means that it is going to write to that file.
The .string() method in QTextStream is only to access the QString used to construct it. In this case, it is zero, since you didn't use a string to construct it.
If you want to access the ... |
7,525,013 | 7,525,178 | Bare minimum of learning in c++ (or what can I skip) | I'm currently cramming up on c++ in order to complete a specific task for my 3rd year Applied Computing degree project. Im by no means a programmer but I am going top have to program an App.
My most comfortable language is c# so this is what I will be using for the bulk of the logic in my app, however I will need to cr... | The WINAPI was originally designed for C. Because of this, you can skip over a lot of the C++ specific parts of C++.
Big stuff to skip:
Objects
Templates
Anything in the STL (Standard Template Library)
Iterators
IO Streams
C++ Strings
Big stuff to focus on:
Dynamic vs Static memory allocation
Pointers
Arrays
C-str... |
7,525,026 | 7,525,174 | Standard string behaviour with characters in C++ | I have a problem which I do not understand. I add characters to a standard string. Whe I take them out the value printed is not what I expected.
int main (int argc, char *argv[])
{
string x;
unsigned char y = 0x89, z = 0x76;
x += y;
x += z;
cout << hex << (int) x[0] << " " <<(int) x[1]<< endl;
}
Th... | You have to account for the fact that char may be signed. If you promote it to int directly, the signed value will be preserved. Rather, you first have to convert it to the unsigned type of the same width (i.e. unsigned char) to get the desired value, and then promote that value to an integer type to get the correct fo... |
7,525,256 | 7,562,783 | C++/CLI DLL project stops linking after conversion from VS2008 to VS2010 | I converted a perfectly working Managed C++ DLL project that uses Unmanaged C++ LIBs from VS2008 to VS2010. Beforehand I separately rebuilt the LIBs with VS2010 (they are part of another project that I have no authority over). However, after conversion my managed DLL project stopped linking giving me few dosen of LNK20... | Finally found it (thanks Hans Passant for the tip!) I had a few files that were still built by VS2008 and that caused the issue. Thanks to everyone who bothered to add a comment.
|
7,525,330 | 7,541,237 | Memory leak detection with boost::test | I try to enable msvc memory leak detection with line number like this snippet I found here:
Detected memory leaks!
Dumping objects ->
C:\PROGRAM FILES\VISUAL STUDIO\MyProjects\leaktest\leaktest.cpp(20) : {18}
normal block at 0x00780E80, 64 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD... | Using Boost.Test you can use --detect_memory_leaks="allocation number"
|
7,525,786 | 7,526,056 | Directx9 methods of drawing models | I was wondering if there is any other method beside the classical
DrawIndexedPrimitive
DrawIndexedPrimitiveUP
DrawPrimitive
DrawPrimitiveUP
DrawRectPatch
DrawTriPatch
for drawing models on the screen.
| if you mean that model is a mesh (set of vertex and textures) and you have file with that model you can try something like this:
// Loading the mesh
LPD3DXBUFFER materialBuffer = NULL;
DWORD numMaterials = 0;
LPD3DXMESH mesh = NULL;
hr=D3DXLoadMeshFromX("d:\\temp\\tiger.x", D3DXMESH_SYSTEMMEM,
d3dDevice, NULL,
... |
7,525,801 | 7,525,894 | Mac C++ GUI coding - comparison to Win32 | I am struggling to find a good tutorial on how a Mac C++ GUI application is structured. Coming from Windows programming I'm used to message loops and window handles... is it comparable on Macs or totally different?
Any links or examples are welcome, particularly those aimed at transitioning from Win32 rather than assum... | I once was in the same situation as you. I would suggest checking out the Mac Dev Center and reading their "Getting Started" guide.
|
7,525,844 | 7,525,921 | What is the LPTSTR equivalent of _strnicmp in windows? | Is there a LPTSTR equivalent of _strnicmp which takes in 2 LPTSTR strings, and number of TCHARs to compare until?
using the c winapi btw
| It is _tcsncicmp, see the documentation.
|
7,525,942 | 7,674,869 | Address of a static variable | I am trying to do a simple class to unique ID conversion. I am thinking about adding a static method:
class A {
static int const *GetId() {
static int const id;
return &id;
}
};
Each class would then be identified by unique int const *. Is this guaranteed to work? Will the returned pointer really be unique... | As I have noticed at least MSVC 2008 or 2010 optimizes the static variable, so that the following GetId function returns same address even for different classes.
static int const *GetId() {
static const int i = 0;
return &i;
}
Therefore address of uninitialized constant static variable may not be used for iden... |
7,525,996 | 7,527,227 | parameter count mismatch in parameterized query | I am using quite a lot of parameterized queries in my code for performance reasons. In short, some of them work, some don't.
I initialize the query during construction of my database wrapper like this:
QString querystring = QString("SELECT somevalue FROM sometable "
"WHERE one_feature = :one_featu... | Usually this error means that the SELECT/UPDATE query itself is incorrect. You did not give the schema of the database so it's not possible to pinpoint which one. So one or more of somevalue, sometable, one_feature, or second_feature is not in the database/table.
|
7,526,091 | 7,526,151 | Capturing additional mouse buttons | Is there a way to capture presses of additional mouse buttons if mouse has more that 2 of them? According to MSDN WM_XBUTTONDOWN is sent for 2 additional buttons only. I need a solution which will work for any mouse, so using features of special mouse drivers is prohibited. I've found in DirectInput documentation enum ... | What about raw input via the WM_INPUT message?
There's a decent explanation of how it works here.
|
7,526,152 | 7,526,298 | Easy rule to read complicated const declarations? | For reading complex pointer declarations there is the right-left rule.
But this rule does not mention how to read const modifiers.
For example in a simple pointer declaration, const can be applied in several ways:
char *buffer; // non-const pointer to non-const memory
const char *buffer; // non-const pointer to const m... | The const modifier is trivial: it modifies what precedes it, unless
nothing precedes it. So:
char const* buffer; // const modifies char
char* const buffer; // const modifies *
, etc. Generally, It's best to avoid the forms where nothing precedes
the const, but in practice, you're going to see them, so you have to
... |
7,526,217 | 7,526,282 | Detecting a bad item inserted into a std::set | Say I have a custom type in my set, and the set/ordering only makes sense if all items have the same value on some property... if an item with a different value is inserted the model is screwed up and I want to protect this.
I thought maybe the comparison function might be a place we could test this (as an assert or ex... | I guess putting it in the comparator could have issues as you've not got any guarantees when it's going to be called. Perhaps some mythical implementation stores items in a list when the number of items is small and doesn't call the comparator until later?
Probably the simplest approach would be to wrap the std::set... |
7,526,226 | 7,526,283 | reverse link list using recursion | I am trying to reverse a link list using recursion. I have written a function "reverse(node* ptr) for this
I am getting output as 40 40 20 while i expect output to be 40 , 20 , 10.
below is the code posted.
class list {
//some code;
void reverse()
{
node* temp = new node;
temp =first;
... | You should get rid of the line ptr =ptr->next;.
The main objective is to print all the nodes that come after the current node before printing value of the current node. So simply a call to reverse(ptr->next) followed by a cout<<ptr->data<<endl should suffice, since the first call takes care of all nodes after ptr. Ther... |
7,526,255 | 7,532,277 | Unknown reference to __dlopen in dlopen | dlopen is located in libdl.a but when I link my application against libdl.a , gcc linker throw this error : unknow reference to __dlopen called in dlopen
Should I import another .a?
| When I try to compile statically a dlopen mockup program, gcc (Archlinux/gcc version 4.6.1 20110819 (prerelease)) tells me:
$ gcc test.c -ldl -static
/tmp/ccsWe4RN.o: In function `main': test.c:(.text+0x13):
warning: Using 'dlopen' in statically linked applications requires
at runtime the shared libraries from the... |
7,526,429 | 7,526,607 | Fluid Simulation using Smooth Particle Hydrodynamics | Actually, I'm developing an SPH simulator using C++ and openGL. There are several problem I've encountered right now,
I make initiation fluid particles on one side of the box (I make box as boundary volume), shape them like box, and give them initial velocity equal zero. Then I start the main loop, viola, the fluids st... | From the image you provided it seems that the simulation started with all the particles in one corner. Since the particles presumably must have some repulsive potential in order to not overlap each other, once the simulation starts this repulsion will force the particles apart.
Then again, you haven't shown any code, ... |
7,526,538 | 7,526,576 | C++ Constructor / Class Question: Error - left of must have class/struct/union | I realise what this error means, the thing that is puzzling me is why I get it. I have emulated the error in this tiny program for the sake of this question. Here is the code:
source file:
#include "RandomGame.h"
using namespace std;
NumberGame::NumberGame(int i)
{
upperBound = i;
numberChosen = 1 + rand() %... | This
NumberGame newNumberGame();
declares a function newNumberGame() taking no arguments and returning a NumberGame.
C++'s grammar is grown over several decades, rather than being designed in a single act of creation. Consequently, it has many ambiguities that needed to be resolved. This ambiguity was resolved for a... |
7,526,550 | 7,551,564 | Instrumenting C/C++ codes using LLVM | I just read about the LLVM project and that it could be used to do static analysis on C/C++ codes using the analyzer Clang which the front end of LLVM. I wanted to know if it is possible to extract all the accesses to memory(variables, local as well as global) in the source code using LLVM.
Is there any inbuilt library... | First off, you have to decide whether you want to work with clang or LLVM. They both operate on very different data structures which have advantages and disadvantages.
From your sparse description of your problem, I'll recommend going for optimization passes in LLVM. Working with the IR will make it much easier to sani... |
7,526,595 | 7,526,836 | What's the duration of "pointer not aliased by any other pointer" implication? | Currently Visual C++ is shipped with runtime where malloc() is decorated with __declspec( restrict ).
MSDN says this decoration states to the compiler that a pointer returned by malloc() cannot be aliased by any other pointer. Okay, two subsequent calls to malloc() indeed return distinct pointers. But what happens if I... | The standard has this to say about "object lifetime" (§3.8 in N3290):
The lifetime of an object of type T ends when:
— if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
— the storage which the object occupies is reused or released.
After you've free'd the block pointed to b... |
7,526,770 | 7,696,958 | live555 problem while streaming over the internet | I've compiled with VS the live555 source code, and it works just fine if I try to stream locally a file
e.g.
Command Line:
live555.exe myfile.mp3
VLC Connection String
rtsp://169.254.1.231:8554/myfile.mp3
but if I try to stream it over the internet, VLC communicates with live555, but live555 won't send data to him
Com... | To troubleshoot:
Are you streaming RTP over RTSP: have you checked the "Use RTP over RTSP (TCP)" option in VLC? You can check this in VLC under the preferences: input/codecs->Demuxers->RTP/RTSP. You can try to see if this solves the problem in which case it could be that UDP is blocked.
You speak of forwarding. Do you... |
7,526,853 | 7,527,145 | Why do std::function instances have a default constructor? | This is probably a philosophical question, but I ran into the following problem:
If you define an std::function, and you don't initialize it correctly, your application will crash, like this:
typedef std::function<void(void)> MyFunctionType;
MyFunctionType myFunction;
myFunction();
If the function is passed as an argu... |
True, but this is also true for other types. E.g. if I want my class to have an optional Person, then I make my data member a Person-pointer. Why not do the same for std::functions? What is so special about std::function that it can have an 'invalid' state?
It does not have an "invalid" state. It is no more invalid t... |
7,527,293 | 7,527,395 | Allocate and initialize pointer in local function | I want to allocate memory and fill it to the pointer, that are one of the function parameter, but I think that I don't get some important thing, help me please.
So, If I do that everything works fine:
void alloc(char **p, int n)
{
*p = new char[n];
}
int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n);
for(int ... | Try (*p)[i] and (*p)[n - 1] instead. The precedence rules cause *p[i] to be evaluated as *(p[i]).
|
7,527,356 | 7,529,515 | Return string array in C++ function | I am new to C++.
For a school project I need to make a function which will be able to return a string array.
Currently I have this in my header:
Config.h
string[] getVehicles(void);
Config.cpp
string[] Config::getVehicles(){
string test[5];
test[0] = "test0";
test[1] = "test1";
test[2] = "test2";
test[3] = "test3";
te... | Maybe it is better to use a vector in this case, but this is not a correct answer for the question. The reason why it doesn't work is that the variable test just exists in the scope of your function.
So you have to manage the memory on your own. Here is an example:
string* getNames() {
string* names = new string[3];
... |
7,527,674 | 7,527,978 | What is the most effective way to move items within a vector? | I've seen some special cases where std::rotate could be used or a combination with one of the search algorithms but generally: when one has a vector of N items and wants to code function like:
void move( int from, int count, int to, std::vector<int>& numbers );
I've been thinking about creation of a new vector + std::... | It's always important to profile before jumping to any conclusions. The contiguity of vector's data memory may offer significant caching benefits that node-based containers don't. So, perhaps you could give the direct approach a try:
void move_range(size_t start, size_t length, size_t dst, std::vector<T> & v)
{
const... |
7,528,162 | 7,528,305 | header guard conundrum - already defined in .obj problem | I have a class (A) which has to include two files, class X and class Y. unfortunately class Y also needs to include class X in it's header file because the constructor takes a pointer to a class X type as an argument.
The potential problem is that there would be a linker error? as class A now has two copies of class X... | If you have the following:
X.h
#ifndef X_H__
#define X_H__
class X
{
public:
int foo() { return 1; }
};
#endif
Y.h
#ifndef Y_H__
#define Y_H__
#include "X.h"
class Y
{
public:
Y(X *pX) { myval = pX->foo(); }
int myval;
};
#endif
something.cpp
#include "X.h"
...
something_else.cpp
#include "Y.h"
..... |
7,528,363 | 7,528,454 | Implementing mbsnrtowcs in terms of mbsrtowcs | In an almost complete effort to port libc++ to Windows, I need the function mbsnrtowcs, and thought that the easiest way would be to implement it in terms of mbsrtowcs:
size_t mbsnrtowcs( wchar_t *__restrict__ dst, const char **__restrict__ src,
size_t nmc, size_t len, mbstate_t *__restrict__ ps )
{
... | There is an issue here (not really related to the const I think).
mbsrtowcs might set *src to NULL.
mbsnrtowcs is supposed to do the same, of course.
However for you here it causes a 2 bugs:
Because you created a local alias, if mbsrtowcs set *src to NULL it is not reflected for the caller of mbsnrtowcs
mbsnrtowcs has... |
7,528,474 | 7,528,598 | C++ object instantiation and scope | I'm coming (very recently) from C#, where I am used to instantiating objects like this:
Phone myPhone = new Phone();
simply writing
Phone myPhone;
essentially creates a holder for a class, but it is yet to be initialised so to speak.
now I'm writing a small class in C++ and I have a problem. Here is the pseudo code:... | If your Phone constructor takes no parameters then your life is pretty simple - you don't need to new up the phone in the Initialize method. It will be created for you when the object is created and the lifetime will be managed for you.
If you need to get parameters to it, and it doesn't have an Initialize() method or ... |
7,528,499 | 7,528,674 | QT Creator - cross platform compiling | Compiling for Windows, Mac and Linux!
Is the only way to do this.... is to install QT Creator on each OS and compile its own version?
(Currently running QT Creator under Mac OSX)
| Qt Creator is just the automation tool, it will create Makefile and adjacent files for you.
If you want to cross-compile, simply extend your Makefile so it could be possible to cross-compile, for example, via:
export TARGET=i686-mingw32
CXX=$TARGET-g++ RANLIB=$TARGET-ranlib AR=$TARGET-ar make -f Makefile.mingw
Referen... |
7,528,898 | 7,528,930 | How to handle the exception? | #include<iostream>
using namespace std;
class test
{
public:
test()
{
cout<<"hello";}
~test()
{
cout<<"hi";
throw "const";
}
void display()
{
cout<<"faq";
}
};
int main... | Your destructor runs outside the try-catch block - t's scope is the main function. but then raising exceptions from a destructor is a Bad IdeaTM.
|
7,528,937 | 7,529,074 | Unresolved external symbol referenced in function | I realize this is a hard one to answer without providing you with huge amounts of code (which I'll try to spare you).
Essentially i'm getting this error in class X, which #includes the class Y header. The class Y header has three definitions for getters
// Getters
static ID3D10Device* PDevice();
static ID3D10Buffer* PB... | First of all this is a linker error.
This linker error means that the mangled name PDevice et al is not found.
Can you make sure that you have an implementation of a function that matches the definition?
Also, maybe obvious but just check that you actualy have an implementation.
If your implementation is in an external... |
7,529,111 | 7,529,239 | Linking problem in dynamic library while mixing C C++ code | I had a C dynamic library, due to some requirement change I have to do some refactoring.
I had following code in one c file.
__attribute__((noinline))
static void *find_document(...)
{
...
}
bool docuemnt_found(const char *name) {
...
find_document(...);
...
}
I separated the docuemnt_found() function in diff... | The problem here is the declaration of the function as static - in C, this says that it should be available to other functions within the same compilation unit (.c file), but not to other functions outside the file. Removing static should solve the problem.
Incidentally, the second function is misspelled - it should b... |
7,529,545 | 7,529,606 | Access violation reading location 0x00000000. 'new' keyword? | I have two classes, A and Bar, both share a header file that has essentially Foo* foo in it. Class A instantiates an object Bar* bar. This works fine. However, if I make the instantiation of the object
Bar* bar = new Bar();
I get an access violation when bar attempts to do something with foo. Why does this make a dif... | 0xC0000005: Access violation reading location 0x00000000.
This means you're dereferencing a null pointer, likely in the constructor of Bar, or in some other code called by this constructor. Use a debugger to determine exactly where.
|
7,529,645 | 7,571,722 | WriteFile() crashes when trying to carry on multithreading | I am working on an mfc dll that is accessed via a script and all this works fine. I have added a multi-threading component to it and am trying to use the WriteFile() function to write to my serial port, but somehow the WriteFile() function exits the application after the 2nd write command gets executed.
Without the mul... | I'm guessing its crashing because you are trying to run that directly from your DLL. Write Function looks fine to me and I think if you try to run your program from the Python script ONLY, it should work. I have faced something similar earlier and came to the conclusion of not running my DLL through the debugger but ju... |
7,529,656 | 7,529,749 | Use a file as a buffer for a producer consumer system of two programs | I have two programs one of which writes some entries into a file and the other one reads all the entries from the file an processes them.
Currently, the files are executed sequentially. That means, the first programs produces the file completely and exits before the second program is run. Now I want, without much modif... | If you are using a Unix-like operating system, may I suggest pipes? Modify your first program to write to standard output (instead of opening a file and passing references that ofstream around, pass std::cout). Modify your 2nd program to read from standard input (ditto, but replace your ifstream references with std::c... |
7,529,704 | 7,532,968 | can we store the value printed by printf() into a unsigned long variable? | I have a following array and a printf() stament,
char array[1024] = "My Message: 0x7ffff6be9600";
printf("%.14s", strstr(array, " 0x") + 1);
The output of above printf() is 0x7ffff6be9600,
can we store it into a unsigned long variable?
| Since you tagged this as C++, see istringstream.
using std::istringstream;
const char source_text[] = "0x7ffff6be9600";
unsigned long value;
istringstream input(source_text);
input >> hex >> value;
|
7,529,725 | 7,529,758 | Unable to create class instance | I have a singleton class that implements two other abstract classes.
My monkey::getMonkey fails because of thisMonkey = new monkey() returns "object of abstract class type "monkey" is not allowed". I know you cannot instantiate abstract classes, but my monkey implements two abstract classes (meaning it is not abstract.... | You don't show enough to say exactly, but a priori, your class monkey
doesn't implement all of the pure virtual functions in the base class. A class which has pure virtual functions which haven't been overridden is abstract.
|
7,529,728 | 7,529,806 | C++ Derived polymorphic class - does it contain an entire instance of Base, including a vptr? | Say we have
Class A
{
public:
int _i;
virtual int getI();
};
class B : public A
{
public:
int _j;
virtual int getI();
};
So assuming that the size of a class in memory is the sum of its members (i.e. ignoring padding or whatever might actually happen), what is the size of a B instance? Is it sizeof... | It's whatever the implementation needs to make the code work. All you
can say is that it is at least 2 * sizeof(int), because objects of
type B contain two ints (and possibly other things). In a typical
implementation, A and B will share a vptr, and the total size will
be just one pointer more than the two ints (modu... |
7,529,881 | 7,531,038 | taking input from a file | i have the following file named asmfile.txt
copy start 1000
read ldx zero
rd indev
rloop tix k100
in order to take linewise input from this file i wrote the following code....
void aviasm::crsymtab()
{
ifstream in(asmfile,ios::in);//opening the asmfile
in.seekg(0,ios::beg);
char c;
string str[3];
string sub... | As to why your code fails: while((c=in.get())!='\n') enters infinite loop when there's no new-line character in the last line of asmfile.
Change i==2?i=0:i++; to i++ and move int i=0; in while loop, edit asmfile so it'll have a new-line character behind last line and your code will work.
That said, you really SHOULD be... |
7,530,015 | 7,544,341 | Validating iphone receipt from c++ | I'm trying to validate an iphone receipt from a c++ server (I have the receipt encrypted with base64, I'm composing a json object according to apple docs, and then I open a socket to the sandbox and send a POST request).
The server responds with error 503 Service Unavailable.
I suspect that I don't compose the POST req... | I solved the problem, in this case the problem was that I was using the http instead of https.
|
7,530,047 | 7,530,161 | Gnu C++ macro __cplusplus standard conform? | The Gnu C++ compiler seems to define __cplusplus to be 1
#include <iostream>
int main() {
std::cout << __cplusplus << std::endl;
}
This prints 1 with gcc in standard c++ mode, as well as in C++0x mode, with gcc 4.3.4, and gcc 4.7.0.
The C++11 FDIS says in "16.8 Predefined macro names [cpp.predefined]" that
The nam... | This was fixed about a month ago (for gcc 4.7.0). The bug report makes for an interesting read: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=1773
|
7,530,121 | 7,612,016 | Conflict between QTMovie / QTMovieView and custom C++ framework | I'm experiencing an insane problem...
A simple Cocoa application with QTMovieView, in which a specific movie file is set or an application which loads and renders QTMovie manually works fine, however if I just link my custom Objective C++ framework, the application always hangs / deadlocks indefenitely right after firs... | Just from your description, it is hard to understand the exact sequence of calls that is going on. However, when I have seen freezes that match the general description of what you are doing in the past, they have usually been static initialisation problems. You mention that you only have static initialisation logic b... |
7,530,175 | 7,530,387 | auto foo = ref new Foo(); What is "ref"? | I was watching a video from, //build/ and several of the MS developers were using a syntax like this in their C++11 programs:
auto foo = ref new Foo();
I understand what everything does in this line except "ref". What does that mean?
| The forthcoming Visual C++ compiler adds this syntax for dealing with WinRT objects (which are in turn the next generation of COM, what have we gone through now? COM, DCOM, COM+, ActiveX, ...)
That line is nearly equivalent to:
com_ptr_t<Foo> foo = CreateInstance<Foo>();
But there's a new version of com_ptr_t as well... |
7,530,425 | 7,530,481 | how to express (5 x 5.4 10-3) in objective-c | I am trying to convert from meter to nautical miles.
I need to multiply meters by 5.4x10-3 but I am not sure how express this number in objective-c.
Any help would be greatly appreciated,
| Like this:
double factor = 5.4e-3;
This means: 5.4 times 10 to the power -3.
|
7,530,453 | 7,530,502 | Internal working of a vector in C++? | Im working on an exercise in C++ but im getting unexpected output I hope someone can explain. The exercise asked that I make a class called rock which has a default constructor, a copy constructor and a destructor all of which announce themselves to cout.
In the main method I am to try and add members of this class to... | When the vector gets resized, the elements have to be moved to their new location.
This is normal.
If you call
byValue.reserve(10);
before any calls to push_back, the extra copies should disappear.
|
7,530,476 | 7,530,505 | Deleting an aliased pointer | Doing this:
union{
int * integer;
char * character;
} u;
u.integer = new int;
delete u.character;
u.integer = new int[5];
delete [] u.character;
I assume this wouldn't work if any of these types have non trivial destructors, but is this ok?
| This doesn't work in any case, if we assume work means having well-defined behavior rather than appearing to work (i.e. not crashing)
|
7,530,507 | 7,532,061 | Logging boost::exception while avoiding file/line/function and the nagging | In my in-house logging library, I am trying to change the custom exception class to derive from boost::exception instead of std::exception. I am doing this so that I can use a single catch block for both boost exceptions and my application exceptions. But I am running into an issue while logging it.
While logging the e... | Alright, I think I found the answer myself. First of all, I don't have to derive my class from boost::exception, I can still continue to derive from std::exception. However, I should throw my std::exception derived class using BOOST_THROW_EXCEPTION. So it becomes boost::exception as it takes off. :-)
In between, I can ... |
7,530,616 | 7,530,650 | override on non-virtual functions | The C++11 FDIS it says
If a virtual function is marked with the virt-specifier override and does not override a member function of
a base class, the program is ill-formed. [ Example:
struct B {
virtual void f(int);
};
struct D : B {
void f(long) override; // error: wrong signature overriding B::f
void f(... |
What if B::f would not have been marked virtual? Is the program ill-formed, then?
Yes, it is. Because in order to override something, that something has to be virtual. Otherwise it's not overriding, it's hiding. So, the positive answer follows from the quote in your question.
|
7,530,724 | 7,530,940 | c++: How to init members of std::pair in constructor | I have the following class:
typedef std::pair<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket> socket_pair;
class ConnectionPair {
private:
socket_pair _sockPair;
public:
ConnectionPair(boost::asio::io_service &ios);
}
How do I init the sockets in the pair in the constructor ? the followin... | If the type is copy-constructible, your code would have worked. I guess (and only guess, because you didn't specify the compiler error) that a socket is not copy-constructible. Since std::pair does not allow in-place factories, you'll have to make your pair a pair of boost::optional's and use in-place factories. See th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.