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 |
|---|---|---|---|---|
5,766,463 | 5,766,487 | How to skip a class with public access to a function? | I have this setup:
class A
{
public:
virtual void Function();
}
class B : private A
{
}
class C : public B
{
public:
// I want to expose A::Function() here
}
I tried to do this by adding:
class C : public B
{
public:
virtual void Function();
}
and
C::Function()
{
A::Function();
}
but I get and "inaccessi... | In B you can change the accessibility of A::Function to protected:
class B : private A
{
protected:
using A::Function;
};
In C::Function (and elsewhere in C) you will then have to refer to the function as B::Function, not A::Function. You could also public: using B::Function; in C instead of implementing a C::Fun... |
5,766,656 | 5,766,806 | pthreads with objects method | I have a little problem in my current project because i do want tu use an objects method when creating my thread. i red that it is impossible without declare this method as static.
Any idea ?
public:
CModelisation (int argc, char **argv, char[]);
~CModelisation ();
void Init ();
void *RunMainLoop... | I believe it's common practice to create a wrapper function for any thread-method:
struct Foo {
void someMethod() {
// ... the actual method ...
}
static void* someMethodWrap(void* arg) {
((Foo*) arg)->someMethod();
return 0;
}
void callSomeMethodInOtherThread() {
p... |
5,766,882 | 5,766,908 | Why is there no 2-byte float and does an implementation already exist? | Assuming I am really pressed for memory and want a smaller range (similar to short vs int). Shader languages already support half for a floating-point type with half the precision (not just convert back and forth for the value to be between -1 and 1, that is, return a float like this: shortComingIn / maxRangeOfShort). ... | Re: Implementations: Someone has apparently written half for C, which would (of course) work in C++: https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/cellperformance-snippets/half.c
Re: Why is float four bytes: Probably because below that, their precision is so limited. In IEEE-754, a "ha... |
5,766,965 | 5,767,007 | Toon shader with textures | I'm trying to implement a toon shader with texture using C++ on opengl 3+ but after a week i only got a color toon shade without textures.
vertex file:
#version 330
// Incoming per vertex... position and normal
in vec4 vVertex;
in vec3 vNormal;
smooth out float textureCoordinate;
uniform vec3 vLightPosition;
uni... | You need another vertex shader input which receives the UV coordinates for each vertex. Forward them to the fragment shader without modifying them directly (using another smooth out output).
In the fragment shader, you'd typically do something like this:
vFragColor = texture(colorTable, textureCoordinate)
* textur... |
5,766,992 | 5,767,020 | How would you approach string wildcards, without just comparing the correct values? | It has come to my attention that there is no standard form of regular expressions for C++. Although there are many ways for you to check for matching values, what happens when you need complicated formula to compare one value to another, without dozens of lines just for nested IF clauses, or extremely long OR statement... | You need look no further than Boost.Regex, or in some modern compilers and libraries, std::tr1::regex.
You may also want to consider using Perl-Compatible Regular Expressions library, PCRE.
EDIT: your clarification of the question to require not using any external libraries, ultimately increases the amount of work you... |
5,767,102 | 5,767,347 | setting DirectX9 surface pixels | I'm trying to set the individual pixels in a D3DSURFACE9 but they're going all over the place.
I think I've done this before but can't seem to get it right this time.
3DLOCKED_RECT lrt;
if(D3D_OK == lpThis->sfRenderingCanvas->LockRect(&lrt,NULL,0))
{
UINT pitch = lrt.Pitch;
VOID *data;
data = lrt.pBits;
UIN... | The pitch value that comes back in the D3DLOCKED_RECT is the number of bytes between the start of each row, not the number of DWORDs. You're indexing into the buffer using a DWORD pointer, so you are effectively using a pitch four times too large.
Try something like this...
DWORD * row = (DWORD *)((char *)lrt.pBits + ... |
5,767,199 | 5,767,267 | Understanding the efficiency of an std::string | I'm trying to learn a little bit more about c++ strings.
consider
const char* cstring = "hello";
std::string string(cstring);
and
std::string string("hello");
Am I correct in assuming that both store "hello" in the .data section of an application and the bytes are then copied to another area on the heap where the poi... | I have stored strings in the 10's or 100's of MB range without issue. Naturally, it will be primarily limited by your available (contiguous) memory / address space.
If you are going to be appending / concatenating, there are a few things that may help efficiency-wise: If possible, try to use the reserve() member funct... |
5,767,249 | 5,767,289 | How do I run through a 2D array that contains 3 values and run a check for the values? | Ok so i really think I'm over thinking this, but I've been programming for 48 hours straight and my mind is gone. Background info: using Visual Studio 2010, creating a console application using C++. I was having trouble with some logic, and got stuck on the following:
I have a 2 dimensional 8 x 8 array, matrix[8][8]. ... | You cannot decide that inside the loop. You only know the result after going through the whole matrix:
bool hasOnes = false;
bool hasTwos = false;
for(row = 0; row < 8; row++)
{
for (col = 0; col < 8; col++)
{
if(matrix[row][col] == 1) {
hasOnes = true;
} else if(matrix[row][col] == 2)... |
5,767,321 | 5,767,607 | How can I access c++ class member function from lua script? | I think the problem I want to solve will an easy one for most of you:)
Suppose I have a class Node which has a member function setPosition(float x, float y, float z). I would like to be able to define a variable of class Node in lua and then be able to use setPosition() function also form the Lua.
I know that there ar... | I'd use Luabind for this. With it you can easily bind C++ classes so they can be created, accessed, and modified in Lua. The code you'd write in C++ might look roughly like this:
module(L) [
class_<Node>
.def(constructor<>)
.def("setPosition", &Node::setPosition)
];
Then you'd be able to say this... |
5,767,344 | 5,767,384 | Write output stream to a string | I have a stream object std::stringstream and I want to get whatever it currently has as a std::string. Is that possible? I want it for output to my graphic console.
| You can use the stringstream::str() method for that: https://cplusplus.com/reference/sstream/stringstream/str/
|
5,767,350 | 5,767,388 | bitmap row size calculation | I found this source which works quite well, I just want to ask about this piece of code which I dont get:
//calculate total size of RGBQUAD scanlines (DWORD aligned)
bih.biSizeImage = (((bih.biWidth * 3) + 3) & 0xFFFC) * bih.biHeight ;
I get why there is "*3", but dont get the "+3" and the bitwise AND with FFFC h... | If you try that out for various values, you'll see it's actually forcing (width * 3) to round up to the smallest multiple of 4 that will contain it. He's probably doing this to enforce things to be 32-bit aligned.
Using python:
>>> f = lambda x: ((x * 3) + 3) & 0xFFFC
>>> [f(x) for x in range(1, 20)]
[4, 8, 12, 12, 16,... |
5,767,392 | 5,767,404 | Large doubles/float/numbers | Say I have a huge floating number, say a trillion decimal places out. Obviously a long double can't hold this. Let's also assume I have a computer with more than enough memory to hold it. How do you do something like this?
| You need arbitrary-precision arithmetic.
|
5,767,416 | 5,767,432 | c++ list random access |
Possible Duplicate:
How to get a certain element in a list, given the position?
so in python you can get an element in a list in a random access fashion....
list = [1,12,3]
print(list[1])
and it prints 12....
can you do the same thing with c++ list?
I'm talking about this: http://www.cplusplus.com/reference/stl/... | In C++, the nearest along to what you want would be a vector:
std::vector<int> v;
v.push_back(1);
v.push_back(12);
v.push_back(3);
std::cout << v[1] << std::endl; // prints 12
You can use the iterators provided to traverse the vector, too. But once you modify the vector (insert or erase), it becomes invalid.
The actua... |
5,767,705 | 5,767,746 | Create a networked virtual HDD/file system | How would i go about creating a networked virtual HDD/file system? By that I mean, once I install the application a new drive (possibly need to create a driver?) shows up on windows (Mac or Linux?) and when you open the drive it shows you files stored on a server somewhere that can be copied to the local file system or... | You'd need to write a filesystem driver. On Linux you can use FUSE if you don't want to do kernel programming, at the cost of performance. I don't know about options for Windows or Mac OS.
You've tagged this question with the Java tag, but you're more likely to have to use C or C++. If your driver will run in a user... |
5,767,728 | 5,767,745 | field has incomplete type C++ | I am trying to make class that has a member of type of it's enclosing class but I get an error saying field has incomplete type. here is an example
class List {
public:
List (int element, List rest) {
_first = element;
_rest = rest;
}
.
.
.
}
Is there a way to fix thi... | Use this:
'rest' should be a pointer to a List.
|
5,767,731 | 5,767,882 | Modifying the Coin Change problem to keep track of what coin is used (not minimum number) | I wrote a simple coin change algorithm that currently finds the minimum number of coins needed to match the amount required to buy something. I'm trying to modify it so that it keeps track of the minimum number of coins of each denomination to be used and I'm falling a bit short. So, if you were to pass the number 6 to ... | This is a very old problem known as the "Change-making problem." See what Wikipedia has to say about it.
It's a form of the knapsack problem, which is not a trivial problem.
|
5,767,871 | 5,768,005 | Best way to return an object in c++? | I'm pretty noobish when it comes to c++, what is the better way of returning an object? I'm coming from the scripting world where Objects are always references, and am trying to achieve the same notion ... I'm basing this off of When to pass by reference and when to pass by pointer in C++?, where one user stated: "A g... | You need to adjust the Channel class itself so that it isn't copyable. If it is copyable, the user can copy it, and nothing you do can prevent it.
If copying is not a meaningful operation, then you can "disable" it. Simply define the copy constructor (Channel(const Channel&)) and the assignment operator (Channel& opera... |
5,767,916 | 5,768,809 | print a series of numbers optimization part 1 | lets say you want to make a program that will print the numbers 1-9 over and over again
123456789123456789123456789
i guess the most obvious way to do it would be to use a loop
int number = 1;
while(true)
{
print(number);
number = number + 1;
if(number > 9)
number = 1;
}
before i go any further, is... | The most obvious way would be this:
for (;;)
{
for (int i = 1; i < 10; ++i)
{
print(i);
}
}
Why you'd want to optifuscate it is beyond me. Output is going to so overwhelm the computation that any kind of optimization is irrelevant.
|
5,767,959 | 5,767,970 | Sorting a vector of struct causes Visual Studio to throw a popup with "Debug Assertion Failed" | I have a simple Rectangle struct with x, y, width, and height, which I thought would be easy to work with vectors but it turned out to be pretty messy.
This is what I have in main:
vector<CvRect> v;
v.push_back(cvRect(50,0,50, 50));
v.push_back(cvRect(150, 0, 50,50));
v.push_back(cvRect(100, 0, 50,50));
sort(v.begin(),... | Your comparator is incorrect. The comparator needs to return a bool: true if a is "less than" b and false otherwise. It needs to provide a strict weak ordering.
|
5,767,986 | 5,767,994 | C++, innerclasses and why you can only create members as pointers to them | Why is it that you can only create a pionter to an inner class as a member of the enclosing class.
How is it aranged in memory and why does it prevent this, ex:
class temp
{
public:
class inner
{
public:
inner(int a = 0) : memberInt(a) {}
const int memberInt;
};
temp(int ... | The above code actually compiles fine for me in g++, assuming I rename the second one (inner i) to inner i2.
This is the exact code I compiled in g++:
class temp
{
public:
class inner
{
public:
inner(int a = 0) : memberInt(a) {}
const int memberInt;
};
temp(int i = 0) : mem... |
5,768,142 | 5,768,150 | what's the difference between object * x and object& x in c++ |
Possible Duplicate:
Difference between pointer variable and reference variable in C++
suppose I'm trying to pass a reference to object x to a c++ function...
what's the difference between
pass(Object * x){
}
and
pass(Object& x){
}
and how would you access the actual object itself when the pointer/reference is ... | The first is a pass by pointer. The second is a pass by reference.
As for usage, a pointer must be "dereferenced" before it can be used. That is done with the * and -> operators:
void do_something(Object * x)
{
Object & ref = *x; // * returns a reference
ref.method();
x->method(); // same as (*x).method()
... |
5,768,215 | 5,768,235 | tallying elements in an array | So, I'm trying to tally the elements of an array. By this I mean, I have a large array, and each element will have multiples of itself throughout the array. I am trying to figure out how many times each element occurs, however I keep running into the issue of there being duplicate tallies. Since "x" could exist at ... | If you can sort the array, simply sort it. Then all you have left is a linear scan of the elements, checking if the element behind this one is the same as the current element (don't forget bounds checking).
|
5,768,316 | 5,768,347 | pop a specific element off a vector in c++ | so suppose I have a vector called v and it has three elements: 1,2,3
is there a way to specifically pop 2 from the vector so the resulting vector becomes
1,3
| Assuming you're looking for the element containing the value 2, not the value at index 2.
#include<vector>
#include<algorithm>
int main(){
std::vector<int> a={1,2,3};
a.erase(std::find(a.begin(),a.end(),2));
}
(I used C++0x to avoid some boilerplate, but the actual use of std::find and vector::erase doesn't req... |
5,768,372 | 5,768,393 | C++ constructors and computed fields | In C++, constructors must initialize const variables using initialization lists.
What if my constructor needs to compute the values of those fields? Say via a database lookup or simple computation.
The factory pattern could be applied here, but it seems a bit heavy. I'm considering static methods like X::GetX(param1, p... | No need for calling a private constructor, you can call static methods (or in some cases, even non-static ones) directly from the initializer list. For example:
class testclass {
public:
testclass::testclass(int n): memberdata(fn(n)) { }
private:
int fn(int n) {
// Various calculations on 'n'
... |
5,768,403 | 5,770,060 | SHFileOperation doesn't move all of a folder's contents | this makes a new folder on the desktop, but it doesn't move the contents of the folder .pfrom to the folder .pTo.
int main()
{
SHFILEOPSTRUCT sf = {0};
TCHAR myt[MAX_PATH];
GetModuleFileName(NULL, myt, MAX_PATH); // puts the currente exe path in the buffer myt
string currentexepath;
int i;
for... | SHFileOperation requires a double null terminated string. But you can't use std::string or std::wstring for that. See also Double null-terminated string.
When you do:
currentexepath += "\\subfolder\\*.*\0";
The + operator of the string does not see the second null-termination, because it stops at the first null.
Here... |
5,768,511 | 5,771,273 | Using SFINAE to check for global operator<<? | I want to have several overloaded, global to_string() functions that take some type T and convert it to its string representation. For the general case, I want to be able to write:
template<typename T,class OutputStringType> inline
typename enable_if<!std::is_pointer<T>::value
&& has_insertion_operator... | I should have simply been more faithful to this answer.
A working implementation is:
namespace has_insertion_operator_impl {
typedef char no;
typedef char yes[2];
struct any_t {
template<typename T> any_t( T const& );
};
no operator<<( std::ostream const&, any_t const& );
yes& test( std::ostream& );
... |
5,768,638 | 5,768,996 | Idea about how to model a building using OpenGL/GLUT? | I'm new to graphics, and I have to make a model of a building for an assignment using only GLUT or OpenGL.
Basically the school building's model( only the exterior portion) is to be made, and I have no clue where to start. Upto now I have drawn polygons, other shapes using GLUT, nothing in which there are multiple shap... | Think about what you want your building to look like, and think about what kind of triangles you need to render in order to make that. You can either draw the entire thing in some sort of modelling software, and then import it into OpenGL, or you can come up with the triangles/textures yourself and do it by hand in Ope... |
5,768,721 | 5,768,802 | Pass-by-value-Result? |
Possible Duplicates:
pass by reference or pass by value?
I'm having difficulty understanding the Pass-by-Value-Result method. I understand Pass-by-Reference and Pass-by-Value, but I'm not quite clear on Pass-by-Value-Result. How similar is it to Pass-by-Value (assuming it is similar)?
Here is the code
#include <iostr... | If you're passing by value then you're copying the variable over in the method. Which means any changed made to that variable don't happen to the original variable. This means your output would be as follows:
2 1
1 3
2 5
If you were passing by reference, which is passing the address of your variable (instead o... |
5,768,729 | 5,768,761 | (C/C++) Structures containing unions containing structures...? | I am programming in linux, which is new to me. I am working on a project to design a 'layer 7' network protocol, and we have these packets that contain resources. And depending on the type of resource, the length of that resource would be different. I am kind of new to C/C++, and am not sure I understand unions all tha... |
Am I failing to grasp a major concept here?
You're missing knowledge of structure alignment. Basically, it forces certain fields to be aligned by > 1 byte boundaries depending on their size. You can use #pragma to override this behavior, but that can cause interoperability issues if the structure is used anywhere out... |
5,769,009 | 5,769,049 | How to get class's function pointer for non-static function from another class's function? | I need to pass class function as argument for glutIdleFunc. This construction doesn't work:
void (*func)(void) = this->step();
glutIdleFunc(func);
and this too:
void (*func)(void) = Core::step();
glutIdleFunc(func);
How can I do it?
Sorry for my stupidity... :)
| In C++, callbacks such as the one accepted by glutIdleFunc() have to be static methods. Try:
class Core
{
public:
static void step()
{
// ...
}
};
glutIdleFunc(Core::step);
|
5,769,031 | 5,769,076 | Why are SDL and OpenGL related? | I was messing around with SDL and found out that you cannot rotate images with SDL. Everywhere the question was asked, people said to use OpenGL to do rotation. I always thought that SDL was completely separate from OpenGL, am I wrong in thinking this? I even found tutorials for using OpenGL within SDL, which confused ... |
SDL is a cross-platform multimedia library designed to provide low level access to audio, keyboard, mouse, joystick, etc. It also supports 3D hardware via OpenGL.
OpenGL is a standard specification defining a cross-language, cross-platform API for writing applications that produce 2D and 3D computer graphics. The inte... |
5,769,140 | 5,769,171 | What is the "template" keyword doing before "class" keyword? | Just some code sample [Not a real life example]
// at file scope
template <typename T, typename U>
struct demo{};
template class demo<int, int>; // is the template keyword optional here?
Is the template keyword optional in line 3? I haven't (often) seen this usage of the template keyword before. Which part of the ... | That's an explicit instantiation.
Typically when you use a template, the compiler generates what you need, as you need it. To provide essential specializations of a class template in a static or dynamic library, however, you want to generate all the members, all at once, to make sure they are delivered to the user.
For... |
5,769,161 | 5,769,176 | getpwuid doesn't set errno |
uid_t userId = getuid();
userId = 999; // cause error
errno = 0;
passwd* pw = getpwuid(userId);
int n = errno; // pw = NULL, n = 0
Running this code in Linux, I get pw = NULL (expected), and errno = 0. According to Linux documentation http://linuxmanpages.com/man3/getpwuid.3.php... | From the documentation:
ERRORS
0 or ENOENT or ESRCH or EBADF or EPERM or ...
The given name or uid was not found.
I fail to see a problem.
|
5,769,314 | 5,770,960 | How to reference files relatively in Xcode 4 (C++)? | I have a c++ project, add a text file to the project, now I can't read from it I remember in XCode 3 there was property in GetInfo of the Project node, to set the build relative to the project directory and that made it work.
But in XCode 4 I can't find such setting or find a substitute I can only reference files if th... | Are you referring to the working directory the executable uses when run? If so, you can set the working directory by editing the scheme.
Choose Edit Scheme from the Schemes popup, then choose the Run action from the side bar. Working Directory controls are near the bottom. Check the "Use custom working directory" box ... |
5,769,376 | 5,769,387 | Decimal to Binary Conversion | I was writing a function for conversion between Decimal and Binary base number systems and here's my original code:
void binary(int number)
{
vector<int> binary;
while (number == true)
{
binary.insert(binary.begin(), (number % 2) ? 1 : 0);
number /= 2;
}
for (int access = 0; access... | When you say while (number), number, which is an int, is converted to type bool. If it is zero it becomes false and if it is nonzero it becomes true.
When you say while (number == true), the true is converted to an int (to become 1) and it is the same as if you had said while (number == 1).
|
5,769,408 | 5,769,444 | What software can visualise VTK file formats? | I run a code which outputs many .vtk files. What software packages can I use to visualise these VTK files?
| Check and see if ParaView is what you are seeking. See this wiki page for the specifics.
|
5,769,474 | 5,769,502 | Could not Understand the usage of map in c++ | Map is a container class that is used to store the aggregate data... Its very easy to retreive the datas stored in it as it uses hash algorithm for retrieval.
map is a key value pair...The data can be retrieved with the corresponding key...
Here in this declaration below I'm defining that the key has to be integer(4 by... | Beata,
I just did a quick google and came up with http://erunways.com/c-using-the-standard-template-library-stl-map-example/ I won't just copy paste that code here... it's only about 50 lines.
I suggest you read through that code, and then compile and run it (as is). If you run into problems or just stuff that doesn't... |
5,769,734 | 5,769,803 | What are the different versions of exec used for in C and C++? | These are all the versions of exec that can be used in C (and C++)
execl
execle
execlp
execv
execve
execvp
What's the difference between them? How do you know which one to use?
| The differences are combinations of:
L vs V: whether you want to pass the parameters to the exec'ed program as
L: individual parameters in the call (variable argument list): execl(), execle(), execlp(), and execlpe()
V: as an array of char* execv(), execve(), execvp(), and execvpe()
The array ... |
5,769,876 | 5,941,074 | glDrawArray() gives a memory exception | While looping through all objects I want to render in my 3D-engine, I get an error when trying to call
glDrawArrays(mesh->primitiveType, 0, mesh->vertexCount);
Because it tries to read from location 0x0000000, so apparently the pointer bound to the mesh->vertexBuffer index points to zero. This all happens within my ... | RenderableObject::RenderableObject(ObjectManager* objectmgr) : Object(objectmgr), visible(true), scale(1.0f), mesh(0) {
mObjMgr->registerRenderable(this);
}
I think here is your problem mesh(0). Maybe you are calling the Draw() method before you initialize this value. Maybe your Renderer class does it.
Try to add ... |
5,769,886 | 5,769,964 | Logical error in retrieving the string from the map-C++ | I could able to run the program but nothing gets displayed..
If I replace .find("1") I'm getting compiler error as const char cannot be changed to const int.
If I replace with .find('1') then I'm getting the output as "string is not in the map".
I need to retrieve the string with the key value 1. How should I modify my... | I don't see your problem to be honest. Your key-type is int, so in find() method you should give this exact int as the key. Code given in your question is OK.
If nothing gets displayed in this exact code you have posted, it is because you do have key (int)1 in your map. To display value assigned to this key, you could ... |
5,770,017 | 5,770,041 | Qt - What is QApplication, simply? | I saw the description of QApplication in the Qt documentation, but wasn't that clear.
Can you just simply describe what it mainly does?
Thanks.
| The most important thing to know about QApplication is that its exec method runs the event loop, which is basically the piece of software that makes slots and signals work.
To put it simply, if there is no running event loop, the events fired by your GUI components will not be propagated at all, so your UI will just no... |
5,770,253 | 5,770,888 | Is there any case where a return of a RValue Reference (&&) is useful? | Is there a reason when a function should return a RValue Reference? A technique, or trick, or an idiom or pattern?
MyClass&& func( ... );
I am aware of the danger of returning references in general, but sometimes we do it anyway, don't we? T& T::operator=(T) is just one idiomatic example. But how about T&& func(...)? ... | There are a few occasions when it is appropriate, but they are relatively rare. The case comes up in one example when you want to allow the client to move from a data member. For example:
template <class Iter>
class move_iterator
{
private:
Iter i_;
public:
...
value_type&& operator*() const {return std::... |
5,770,298 | 5,770,312 | combine a char and an int to a string | For example;
int i = 1;
char c = 'V';
string s;
Result:
s = "1 V"
Can anybody tell me how to do that?
Thank you
| Use std::stringstream from <sstream> header file, as:
#include <sstream>
int i = 1;
char c = 'V';
std::stringstream ss;
ss << i << " " << c;
std::string s = ss.str();
std::cout << s;
Output:
1 V
I've implemented stringbuilder using which you can do this just in one line:
std::string s = stringbuilder() << i << " "... |
5,770,553 | 5,770,744 | GDI+ performance for pixel level rendering | I am doing some animation based on an algorithm that is supposed to render a scene at 800 x 600 resolution. It will essentially be redrawing each pixel for every "frame" at, hopefully, no less than 30 FPS.
Would this be possible?
I guess I would be drawing bitmaps.
Thanks
| The fastest bitmap pixel format on most hardware is 32PArgb. A 800x600 bitmap takes about 8.5 milliseconds on my laptop when drawn unscaled with Graphics::DrawImage(). It has decent graphics hardware. This goes up to 12 msec for other pixel formats.
What you can't predict is how much time you'll burn rendering the s... |
5,770,634 | 5,770,757 | Copy-elision of automatic variable for return | I am wondering if in C++0x "12.8 Copying and Moving class objects [class.copy] paragraph 31" when copy elision happens, exactly:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...]. This elision of copy/move
operations, called copy elision, is permit... | Yes, copy elision is possible/allowed in both cases.
In compiler terminology, the two cases are slightly different though. return {"House", "Horse", "Hen"}; constructs an unnamed object, so regular RVO kicks in.
return res; is slightly more complex, because you are returning a named object which was already constructed... |
5,770,718 | 5,770,735 | const_cast in c++ -getting errors | include "stdafx.h"
#include <iostream>
using namespace std;
class Foo{
public:
void func()
{
cout<<"Hello!!"<<endl;
}
};
void some_func(const Foo &f)
{
//f.func();
Foo &fr=const_cast<Foo&>(f);
fr.func();
}
int main()
{
some_func(Foo &f); //if const declared will add the no of error... | Your problem is probably with main()
int main()
{
Foo f;
some_func(f);
return 0;
}
You need to declare f before you can use it.
|
5,770,754 | 5,771,228 | C++: std::istream check for EOF without reading / consuming tokens / using operator>> | I would like to test if a std::istream has reached the end without reading from it.
I know that I can check for EOF like this:
if (is >> something)
but this has a series of problems. Imagine there are many, possibly virtual, methods/functions which expect std::istream& passed as an argument.
This would mean I have to... | That's impossible. How is the IsEof function supposed to know that the next item you intend to read is an int?
Should the following also not trigger any asserts?
while(!IsEof(in))
{
int x;
double y;
if( rand() % 2 == 0 )
{
assert(in >> x);
} else {
assert(in >> y);
}
}
That sai... |
5,770,760 | 5,770,878 | How detect and handle if object is used as l-value or as r-value? | I have a container class called Properties. I want to add to it operator[](const std::string & name) which will return property with specified name.
Now lets consider that there is no property with specified name. In this case I wan't to add new Property with specified name to my Properties if it is used as l-value and... | You can cover the cases you give, but not by actually checking whether lvalue-to-rvalue conversion occurs. I don't think it's possible to directly intercept that, so you need to provoke a different conversion instead:
operator[] returns a proxy object, as John Zwinck says. Just creating this proxy object doesn't creat... |
5,770,852 | 5,770,866 | Does Java provide 'friend' access modifier? | I wonder if Java provides 'friend' (as in C++) access modifier? Someone said we can tread 'friend' as default modifier in Java. Is it true?
| The default access modifier in Java allows members to be accessed by any code in the same package.
|
5,770,979 | 5,770,989 | C++ functions problem | Is there a way for functions to call each other i.e.
void menu()
{
some code here
play();
...
}
int play()
{
...
menu();
...
return 0;
}
| Add the declaration of the second function at the top of your code file:
int play();
void menu()
{
// some code here
play();
// ...
}
int play()
{
// ...
menu();
// ...
return 0;
}
This is called a forward declaration, and it informs the compiler that an identifier will be declared later.
It is ... |
5,770,984 | 5,771,007 | c++ main() brain teaser | Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?
My answer is during the initialization of static variables, but not sure...
| A very simple example
struct abc
{
abc()
{
int* p = 0;
*p = 42; // Drat!
}
};
abc obj;
int main(){}
|
5,771,022 | 5,771,065 | How can I count amount of sequentially set bits in a byte from left to right until the first 0? | I'm not good in English, I can't ask it better, but please below:
if byte in binary is 1 0 0 0 0 0 0 0 then result is 1
if byte in binary is 1 1 0 0 0 0 0 0 then result is 2
if byte in binary is 1 1 1 0 0 0 0 0 then result is 3
if byte in binary is 1 1 1 1 0 0 0 0 then result is 4
if byte in binary is 1 1 1 1 1 0 0 0 t... | Easiest non-branching solution I can think of:
y=~x
y|=y>>4
y|=y>>2
y|=y>>1
Invert x, and extend the lefttmost 1-bit (which corresponds to the leftmost 0-bit in the non-inverted value) to the right. Will give distinct values (not 1-8 though, but it's pretty easy to do a mapping).
110* ****
turns into
001* ****
001* *... |
5,771,057 | 5,783,181 | Box2d Loop Shape / create static ground shape in Cocos2D | Does anyone know what is the best method to create a static ground body with many (~10000) vertices in Box2D (the version that comes with Cocos2D).
This is what I do now for cubic beziers, it looks fine but runs a bit slow.
for (int i = 0; i<segments; i++) {
CGPoint p2 = vertices[i+1];
CGPoint p1 = vertices[i];... | For b2LoopShape, you need to replace external/Box2d with Box2D trunk.
checkout Box2D trunk from box2d.
replace cocos2d/external/Box2d with trunk/Box2D/Box2D.
modify Xcode project for added Box2D files.
modify some codes for renamed classes such as s/b2DebugDraw/b2Draw/.
|
5,771,075 | 5,771,099 | Generating random graphs | I need to generate random single-source/single-sink flow networks of different dimensions so that I can measure the performance of some algorithms such as the Ford-Fulkerson and Dinic.
Is the Kruskal algorithm a way to generate such graphs?
| To create a generic flow network you just need to create an adjancency matrix.
adj[u][v] = capacity from node u to node v
So, you just have to randomly create this matrix.
For example, if n is the number of vertices that you want ( you could make that random too ):
for u in 0..n-1:
for v in 0..u-1:
if (ran... |
5,771,131 | 5,771,143 | Nested templates vs shift operator | I have been reading all around about be aware >> as ending of nested template and >> as shift operator...
Now I have tried it in my MSVS2010 and no problem occured.
std::map<int, std::pair<int, int>> m;
This code works exactly what I want (map of pairs) but I supposed to get some error about >>
Compiler is smarter thes... | MSVC++2010 supports C++0x feature Right Angle Brackets
|
5,771,162 | 5,771,177 | c function interface question | extern "C" int func(int *, Foo);
This is from a sample code from class. But I don't understand how the interface is working, one with no variable name, the other with no type. How is that going to work?
| When declaring functions you don't need to specify a parameter name, just a type. Foo in this case is a type.
extern "C" tells the compiler it should use a C-style symbol, which more or less means it won't be using name mangling (which C++ uses to allow multiple functions share a name, but use different parameter sets ... |
5,771,171 | 5,771,502 | Does return value optimization work, when assigning to a different type? | Consider the following two classes:
class Base
{
Base(const Base& other) {...} // relatively expensive operations here...
Base(int i) {...} // ...here,
virtual ~Base() {...} // ...and here
...
};
class Derived : public Base
{
...
Derived(const Base& other) :Base(other) {...} // so... | This is bad.
Derived(const Base& other) :Base(other) {...}
The static type of other can belong to the derived type. In that case it will get sliced. On top of that base class would be copied anyway.
RVO is about bypassing copy constructor and initialising the returned object in-place. If you need an object of the d... |
5,771,192 | 5,771,395 | OpenGL Lighting Quads | just a quick question. I have a quad in 3D OpenGL scene. I define a normal to the plane counter clockwise. So that the normal points out one side of the plane. In the direction of my light source. The quad is light but on both sides.
Should it not only be light on one side of the quad? Or is it the fact that a primiti... | The default OpenGL lighting behavior for two sided polygons is to calculate lighting for the front face and apply it to both sides.
You can get around this by using a front and back polygon with seperate normals for each of your double sided polygons.
Alternatively, you can enable GL_LIGHT_MODEL_TWO_SIDE for lighting c... |
5,771,292 | 5,771,403 | is there a DWT function in opencv? | is there a DWT (discrete wavelet transform ) function in opencv ?? else if anyone have link of its implementation in c++
| It appears that openCV does not have an implementation of the DWT algorithm, but a quick google search turns up two results which may be relevant.
First is a result from Koders code search, which is an implementation designed to process MPEG4 frames for an image decoding program.
There is also a google code project, wa... |
5,771,314 | 5,771,333 | no matching function for call to function template | template<class T, T i> void f(int[10][i]) { };
int main() {
int a[10][30];
f(a);
}
Why does f(a) fail?
http://ideone.com/Rkc1Z
| f(a) fails because a template type argument cannot be deduced from the type of a non-type argument. In this case the compiler cannot deduce the type of the template parameter T.
Try calling it as f<int>(a);
|
5,771,486 | 5,772,060 | Is it possible for Radeon cards to read data from DisplayPort (using OpenCL)? | Radeon is about to release videocards with DisplayPort. What I need to do is instead of using host memory (RAM) I want to read data passing from Pegasus R6 (direct-attach RAID device) straight to video card. Perhaps using OpenCL and utilizing C/C++ on host to control the flow.
http://www.promise.com/storage/raid_serie... | There have been ATi-based cards with DisplayPort such as the PowerColor AX5770 (which I use) for a while now. But you are talking about connecting a storage device to a video card, and this is not feasible as far as I can tell. The storage device you mentioned has a Thunderbolt interface, but while Thunderbolt does s... |
5,771,507 | 5,771,845 | Linking custom object files with Cabal | In a custom cabal hook I generated object files (*.o) which I want to pass to the linker. How do I do this idiomatically?
Solution
Don Stewart's answer goes in the right direction. Currently I do the following:
$ runhaskell Setup.lhs build --ld-options="PATHS TO .o FILES"
| According to the Cabal documentation for UserHooks, it looks like you'll need to add a buildHook, by specifying additional build flags, that add your .o files to the buildFlags for ld.
As an aside, you should be aware that generating custom .o files is highly unusual, and likely to make your build fragile. Is there a ... |
5,771,636 | 5,772,571 | InternetOpenUrl only returns after entire HTTP response is downloaded | I am writing a download file utility using WinINET, and have noticed (especially on large downloads), that the WinINET InternetOpenUrl() call only returns after the entire HTTP response has been downloaded.
I confirmed this by using the Charles proxy tool, as well as using WireShark, and noticed that the download compl... | I know its probably not polite to answer your own question, but I believe I tracked down what the problem was.
After a reboot (and many, many, many minutes wasted on Automatic Updates) I tried again, and experienced the same problem, but I took solice from Alex K. and J.J.'s comments suggesting this is not the expected... |
5,771,714 | 5,771,922 | How to bind overloaded functions with Luabind? | I am writing a game engine in c++ which will provide Lua scripting ( for which wrapping I am using Luabind ) and I am having some problems to bind overloaded functions. Namely: I have am overloaded function :
void setGlobalPosition(const Vec3& position);
void setGlobalPosition(Real x, Real y, Real z);
And I would like ... | As DeadMG pointed out, you are missing an ampersand before the member function. The tutorial you linked is also missing it. Some compilers might not care, but g++ does and probably some others do too.
|
5,771,788 | 5,771,805 | Ensuring at most one process is running at a time | There are several applications, more than one process of which cannot run at a time. For example, we cannot run two instances of Window Media Player. Even if we click on the exe multiple times, another process will not start!
I was wondering how to do that in the following situations :
if the application is developed ... | Typically the application needs to try to acquire some unique resource on startup; if it fails, it should exit. The nature of the unique resource varies by environment -- for example, it could be listening on a particular TCP port, or locking a file or shared memory segment. The program then needs to be careful to free... |
5,771,823 | 5,771,865 | Is .LIB file needed to call DLL in C++ but not for C# P/Invoke? | I have been looking for answers on how to reference unmanaged DLLs from C++,
Is there a better way to load a dll in C++?
DLL References in Visual C++
and it appears that a DLL cannot be loaded in C++ without the caller also having the .LIB file. Is this true that the .lib file is absolutely required if I want to dynam... | LIB files are only needed if you want to link statically (forcing a strong dependency between your binary and the DLL: your binary won't load if the DLL isn't present). LoadLibrary() (or LoadLibraryEx()) bypasses all that: but on the other hand, you have to setup function pointers to all entry points using GetProcAddr... |
5,771,868 | 5,771,886 | How to allocate memory space without using malloc or new operator? | When my friend had his interview yesterday, he was asked a question:
Implement a function that allocates memory space without using the *alloc or new operator, and the function should return a pointer to the address.
Neither he nor I can find the answer.
| I think the question is more of a puzzle than a question that shows experience with programming. My solution would be allocating a global byte-array, that would be used instead of the heap:
char heap[MAX_ALLOWED_MEM];
/*
The following function uses 'heap' as raw memory!
void* like_malloc(size_t bytes);
...
*/... |
5,772,083 | 5,772,098 | how to store the bit string in array? | how to count number of occurrences of 1 in a 8 bit string. such as 10110001.
bit string is taken from user. like 10110001
what type of array should be used to store this bit string in c?
| Short and simple. Use std::bitset(C++)
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> mybitstring;
std::cin >> mybitstring;
std::cout << mybitstring.count(); // returns the number of set bits
}
Online Test at Ideone
|
5,772,136 | 5,772,153 | C++: How to create enum within a function? | I want to simplify things, by not creating a list of enum separately, but create the enums along the function call which creates the data where i point with those enums.
I tried to make #define which would create another #define, but it didnt work:
int defcounter = 0;
#define make_def(enumname, somedata) \
#define... | It is impossible to create new types (classes, enums, unions, whatever) at runtime in C++. One of the major features of C++ is that it is statically typed - all types must be known at compile time.
|
5,772,224 | 5,838,602 | How to mix voice audio | I am currently developing a simple VoIP project where multiple clients send out his voice to a server and later the server will mix up those voices together.
However, I can't mix it directly by using simple mathematic addition. Each cycle, a client will send 3584 Bytes voice data to the mixer.
Below is the snippet of t... | I looked at your data again and they appear to be floating point values the reason I was mistaken in my previous post is probably related to me working on big endian systems for a while now. However your data is in little endian IEEE floating point. Here are the values I got after conversion.
0.089630127 -> 0x0090b73d
... |
5,772,289 | 5,772,547 | calling of operator = from within derived class | This is from the item 16 of effective C++ 2nd edition scott meyers (page 70)
Author writes without much explanation that when base class operator = is called in the following fashion
Base::operator=(rhs);
some compiler (though incorrectly) reject this, if the operator = was generated by compiler(see item 45) so better... |
but in original question compiler was
rejecting it because it was generated
by compiler (which has to be public)
Maybe I understand what you want.
Compiler generated assignment operator becomes public. But item 16 isn't about access level. This static_cast<base&>(*this) is a workaround for broken compilers. In i... |
5,772,308 | 5,772,338 | C++ filestream problem | I'm making a simple game in C++ and I want the highest score at the end of the game to be written in a text file. I'm using fstream to first read the last saved highscore and compare it to the new highscore. The output in the text file looks like this (0НН) and it shouldn't. I'm realy frustrated with this.
Here's a par... | #include <iostream>
#include <fstream>
using namespace std;
#define SPEED 12
int main()
{
double score_num=0;
ofstream datafile("score.pon"); //Declaration of variables
if(SPEED>score_num)
{
score_num=SPEED;
}
//getting the score
datafile<<score_num; //Writing it to the file
... |
5,772,480 | 5,924,594 | Portability of Native C++ properties | In Visual Studio, there is __declspec(property) which creates properties similar to C#. Borland C++ offers the __property keyword with the exact same functionality. In the C++0x, there is mention of a implicit keyword that could be expanded to implement the same functionality. But it didn't make it into the spec.
I... | This is something similar to what you are asking and is (I hope) standard C++...
#include <iostream>
template<typename C, typename T, T (C::*getter)(), void (C::*setter)(const T&)>
struct Property
{
C *instance;
Property(C *instance)
: instance(instance)
{
}
operator T () const
{
... |
5,772,630 | 5,772,646 | question on c++ reference | suppose I have this vector
vector<Object> m;
and then I have the following assignments:
vector<Object> o = m;
vector<Object> k = &m;
vector o will be a COPY of vector m whereas vector k will point to the exact same object as vector m....am I right?
in other words, if I go, o.push_back(something), this will modify vec... | Right for o, wrong for k.
vector<Object> k = &m;
// ^^ -- you're taking the address of m here
To make a reference, use
vector<Object>& k = m;
// ^ -- this makes a reference
|
5,772,639 | 5,772,704 | Sorting for the heck of it -- Quicksort | We have to make an optimized quicksort for out own Comparable base class. For the life of me I cannot make it work. The algorithm seems straight forward, however I cannot seen to get my code to work. I have a DateTime class that extends Comparable that I am using to test and the sort seems to work but one out of every ... | From the code you've shown us and your comment about what goes wrong my only guess is that from and to do not mean what you think. Your code has to - from as the length of the segment to sort. If that's exact (and not just approximate for pivot selection) that would mean that to was actually pointing at an element ju... |
5,772,693 | 5,772,725 | COM reference counting - thread safety | If I have a COM object, is it required for the AddRef() and Release() methods to be thread-safe- i.e., that I have to use atomic operations for my ref count?
| Yes, if you are using the free threaded aparement model, use InterlockedIncrement() and InterlockedDecrement() to handle the ref count.
|
5,772,814 | 5,772,883 | Is a comparison an atomic operation? | Is the following comparison an atomic action? I.e., can it be reduced to a single CPU instruction?
char flag = 2;
for(;;)
{
if (!flag) // <-- this
break;
// sleep
}
Here's what I'm doing:
int main()
{
sf::Mutex Mutex;
char flag = 2;
coordinatorFunction(flag);
for(;;)
{
i... | This is the wrong way to go about it.
Your main thread is burning up CPU cycles as fast as it can, doing nothing but waiting for flag to reach zero. This test will fail every time it's attempted, except the last one. Instead of doing it in this manner, use the "join" facility that your thread objects most likely have t... |
5,773,024 | 5,774,690 | wxWidgets wxThread Delete for a Joinable Thread | I got a question about joinable threads in wxWidgets.
When the user wants it, I want to stop a thread doing some work. For that reason I call in this worker thread TestDestroy() to check whether the thread should be stopped. But I can only stop the thread this way by calling Delete(), which should not be called for joi... | The current documentation for wxThread::Delete() says:
This function works on a joinable thread but in that case makes the TestDestroy() function of the thread return true and then waits for its completion (i.e. it differs from Wait() because it asks the thread to terminate before waiting).
So, it appears that you ca... |
5,773,108 | 5,773,127 | Initializing series of arrays with for loops at C++ | I try to create series of multidimensional arrays with for loops. User should input the number of arrays to be initialized. I want something like this:
int i;
printf("Enter the number of arrays you want: ");
scanf("%d",i)
for(int j=0;j<i;j++){
long double x(j)[size][size];
}
if I input 5, I want to have x0, x1, x... | Edit: Just noticed you are using C++. In this case, std::vector is definitely the most convenient solution. If you are curious about how to do this with plain arrays, C style, then read on...
You can't do it like this. What you need to do is create a 3 dimensional array (or an array of 2-dimensional arrays, depending ... |
5,773,144 | 5,773,164 | regarding file existence check within a for loop in C++ | I am attempting to check if a file exists, and then if so proceed with a task and if not to just output that there is no such file. I have done this in other code but it doesn't seem to be working with my current code.
The basics of it read:
count=argc;
for(i=0; i < count-1; i++)
{
filename[i] = argv[i+1];
}
f... | You need to call infile.is_open(). Also, do you plan to do something with the file if it exists, or not?
|
5,773,188 | 5,773,229 | Copying and then sorting a linked list | I have a linked list of Nodes, each Node is defined as:
struct Node {
char name[14];
int counts[130];
char gender;
Node *nextPtr;
};
I am copying this linked list with the following code:
// Create a copy of the current list
Node *tempPtr;
while (headPtr != NULL) {
tempPtr = new Node;
tempPtr = hea... | There's no such thing as new in C. Are you using a c++ compiler?
Ignoring that, the problem is you aren't copying anything, and in fact are creating a memory leak:
tempPtr = new Node;
tempPtr = headPtr;
You create a new node on the heap, assigning the pointer to tempPtr ... then reassign tempPtr to headPtr. You just... |
5,773,388 | 5,773,488 | C++ ODBC SQL_ATTR_PARAMS_STATUS_PTR missing in header | I am trying to bind a structure with Rowset binding ala:
http://msdn.microsoft.com/en-us/library/aa215456(v=sql.80).aspx
THIS IS AN MSDN TYPO!
| It's in sqlext.h, so:
#include "sqlext.h"
Unless you wish to have the difference between sql.h and sqlext.h as your specialist subject in a quiz program, you are better off always #including both of them, without thinking.
|
5,773,390 | 5,773,475 | C++ network programming | I would like to expand my knowledge in C++, so the first thing I'm taking on is network programming.
I want to make an IRC bot (which hopefully will teach me about socket programming and networking topics), but I have no idea where to start. If anyone could explain to me how IRC bots work and how to make them, and dire... | To understand sockets and use them right, you need The Sockets Bible:
W. Richard Stevens, Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition)
You absolutely must have this book before you sit down to write a line of sockets code. Don't leave home without it. Really. Starting around $35 used at ... |
5,773,395 | 5,906,229 | Pass nested C++ vector as built-in style multi-dimensional array | If I have a vector in C++, I know I can safely pass it as an array (pointer to the contained type):
void some_function(size_t size, int array[])
{
// impl here...
}
// ...
std::vector<int> test;
some_function(test.size(), &test[0]);
Is it safe to do this with a nested vector?
void some_function(size_t x, size_t y... | Trying to use &top_level_vector[0] and pass that to a C-style function that expects an int* isn't safe.
To support correct C-style access to a multi-dimensional array, all the bytes of all the hierarchy of arrays would have to be contiguous. In a c++ std::vector, this is true for the items contained by a vector, but n... |
5,773,480 | 5,773,493 | How to solve this: "cannot convert parameter 1 from 'const GLdouble' to 'const GLdouble *"? | In a calling to an OpenGL function, I had the following error:
error C2664: cannot convert parameter 1 from 'const GLdouble' to 'const GLdouble *'
Is it strange a bit !!
const GLdouble someColor = 30.0;
The calling:
glColor3dv(someColor);
Any help!
| glColor3dv takes a pointer to the initial element of an array of three GLdoubles (one each for the red, green, and blue channels). You are passing it a single GLdouble by value.
Either you need an array of GLdoubles or you need to use one of the other glColor functions (like glColor3d).
|
5,773,553 | 5,773,598 | c++ 2d plotting tool for linux | I am looking for a simple c++ 2d plotting tool for Linux (to be more honest "Cross-platform").
"koolplot" is nice but I think it's for windows only since its code includes graphics.h and windows.h.
Someone suggested Qt's QPainter, but I cannot even use it to draw a single point. :'(
So, is there any help on other plott... | Check out Qwt. It's worked well for all of my 2D applications, plus it's cross-platform.
|
5,773,660 | 5,773,748 | c++ vector of pairs of pointers screw up | so I have a vector of pairs of pointers in c++:
vector<pair<Move *,Piece *> > moveList;
where Move is an object and Piece is an object...
Piece has the class variables type and side
so I add stuff to moveList:
pair <Move *, Piece *> pr (&m,&(p));
moveList.push_back(pr);
where m is a Move object and p is a P... | As others have pointed out, it's seems you may be holding pointers to objects on the stack. These objects will go out of scope once you exit the function/block. Since STL containers manage their memory internally, one approach could be to change the vector to hold objects directly instead of pointers.
vector <pair <Mov... |
5,773,826 | 5,773,835 | Child commands in popen telnet | I am trying to establish a local telnet session in C++ and send commands/receive data. Right now I have:
const char *cmd = "telnet 127.0.0.1 2006";
char buffer[256];
FILE *pipe = popen(cmd, "rw");
//if( !pipe ) { perror("popen"); exit(-1); }
while( fgets(buffer, sizeof(buffer), pipe) != NULL &&
!feof(pipe... | Using telnet seems like a rather roundabout way to do this. Have you considered using regular sockets to talk to the remote process? For example, try this guide to socket programming.
|
5,773,882 | 5,774,593 | std::remove is not removing from std::vector | Here is my issue:
In my GUI, there are several types of listeners. They are stored in std::vector<WhateverListener*>
In my GUI, I have a method called removeListeners and it looks like this:
void Widget::removeListeners( Widget* widget )
{
removeFocusListener((FocusListener*)widget);
removeMouseListener((MouseL... | The root of your issue seems to be an incorrect design. The need to cast as you are doing implies that the function is in the wrong place. It's not clear from your post what the relationship between Widgets and the different types of Listener classes are.
You need to rethink where you are calling the removeListeners f... |
5,774,295 | 5,774,884 | CYGWIN: Variables in memory spontaneously changing values | Some of my variables change values seemingly unjustifiably when I change other variables in my c++ code. I've used gdb to hardware watch the memory in question and it will occur even when I just cout << "bla";
If anybody could offer ANY suggestions as how to fix this, it would be greatly appreciated! I'm stumped!
Whe... | The most likely cause of a variable "spontaneously" changing value is a buffer overflow. The next most likely cause is heap corruption (or using memory after it has been free()d or deleted (aka dangling memory)).
You didn't say whether the variables that change are global, heap allocated, or local. I am guessing heap a... |
5,774,388 | 5,774,397 | C++ std::vector<uint8> filled, but data is not displayed | Heres my code:
std::string message(m_buff.begin(), m_buff.end());
std::cout << "Client wrote sth!" << std::endl;
std::cout << message.c_str() << std::endl;
If i set a breakpoint in the last line, start the debuger and lookup the m_buff var, there is some data, but it didnt get displayed.
Heres the Data (from debugger... | Assuming that the data displayed by the debugger is correct, it seems as if you're having some binary zeroes in your message buffer.
Remember, a binary 0 ('\0') is used to indicate the end of a string. So, as the first element of m_buff is a zero, the string has effectively length 0.
You should perhaps iterate m_buff a... |
5,774,429 | 5,774,467 | Need help with C++ to Java translation | Here is the C++ code
public class First {
public:
virtual int firstmethod(int a, int b) = 0;
virtual int secondmethod(int a, int b, int c) = 0;
}
public class Second : public First {
public:
int firstmethod(int a, int b) {
int result = a * b;
return result + 3;
}
}
Here is what i... | It would be something like :
public class Whatever {
public int mymethod(int one, int two) { return 0; }
public int myothermethod(int one, int two, int three) { return 0; }
}
public class However extends Whatever
{
@Override // optional annotation
public int mymethod(int one, int two)
{
int answer =... |
5,774,529 | 5,774,552 | help with fixing memory leak | i have a member function in which i need to get some char array at run time
My fear
Is if i try
delete buffer;
then i cant
return buffer;
But how to i release the memory i allocated with
char * buffer= new char[size]
The class
class OpenglShaderLoader
{
char * getLastGlslError()
{
... | You should return a std::vector<char>. That way, when the caller finishes using the vector, its contents are freed automatically.
std::vector<char> getLastGlslError()
{
int size;
glShaderiv(hShaderId, GL_INFO_LOG_LENGTH, &size);
std::vector<char> buffer(size);
// fill in the buffer using &buffer[0] as t... |
5,774,642 | 5,775,038 | Any limitations using C++ STL for iOS development? | My purpose is to reuse some C++ STL implementation for iOS development with static library.
As we know, iOS devices are based on ARM6/7 family,which is different with *86 family for some compiler options.
For mobile development, we prefer to reuse some C++ codes across different platforms,such as iOS, Android, and ev... | The main purpose of using standardized tools is to achieve portability. As long as you use the library as intended, without relying on behavior outside the standard, there should not be any issues moving it to any platform with a good C++ implementation.
The Standard Library implementation on iOS is the same as the one... |
5,774,733 | 5,774,745 | Outcome of the C/C++ code |
Possible Duplicate:
Undefined Behavior and Sequence Points
What is the outcome of the following code:
#include <stdio.h>
int main() {
int a = 3;
a= (a = 2) + (a = 3);
printf("%d", a);
}
Why do I get 6 as the output on gcc? Why not 5?
| You're both writing and reading variable a between sequence points, so the result is formally undefined behavior.
Looking at the assembly code generated by your particular compiler will make it clear why you get a particular result, but the standard makes no guarantees at all.
|
5,774,766 | 5,774,920 | Race condition with self | I have a class with member functions that require a boost::unique_lock be acquired on the respective mutex before performing their operation.
However, when the member function is called when there is an existing boost::unique_lock it deadlocks itself.
#include <iostream>
#include "boost/thread.hpp"
#include "boost/fore... | I haven't used boost threading, but if I read your code correctly you lock the mutex in your main function then you call the examlpe_instance's next() method which also tries to obtain a lock on the array mutex... naturally that would cause a deadlock, since it doesn't seem like the lock is re-entrant.
Why are you acqu... |
5,774,943 | 5,775,016 | Why doesn't my vector recognize my derived classes? | I have a huge problem, much bigger than what I'm going to post, but if someone can help me with this, then it will be smooth sailing from here.
Okay, so my vector of pointers REFUSES to recognize its derived classes. Let me explain.
I have a class of Player objects from which Warrior and Wizard derive from.
The assignm... | You are receieving this error because when you are dereferencing pointer to Player here, you get Player object, not Warrior or Wizard:
cin >> *players[i]
And Player object don't have operator>>() as you have said.
Possible solutions:
1. use dynamic_cast to cast from Player* to Wizard* or Warrior* at runtime. You can ... |
5,775,013 | 5,775,274 | Using CLists in c++ -Could not understand | I searched for a sample program to work on with the CList.But i could not find it.I got some basic definitions about the CLists(template class that behaves similar to the doubly linked lists).. and is used to store the aggregate data..The 1st argument is stored internally by the list..I could not see what elements are ... | So the doc is CList on MSDN
And there is a link there for the COLLECT Sample: Illustrates MFC Collection Classes
I'm not sure how this doc was not found, so perhaps your question needs to be clarrified.
The list offers front/back inserting and looking, aswell as methods for iterating.
// Define myList.
CList<CString,CS... |
5,775,206 | 5,778,049 | Running two instances of a same C/C++ program on two different input data sets | Once an object file of a program is created does it matter if I run only one or multiple instances of it on different input data sets? Is it possible that outputs corresponding to these runs may be correlated to each other?
With regards
newbie
| For a properly designed program, having multiple simultaneous instances should be fine. Each process is separate from all others, with its own address space, its own file descriptors and its own part of all other resources. As long as the output files are separate, all should work in parallel as they would on their own... |
5,775,228 | 5,775,381 | Template functions and class use in different files | I want to have a template function defined in one file and used in many files. Does this work the same way regular function prototypes work? So I can define it once and just include the prototype in other files? I have the same question for classes, must I include the full defintion of a template class in each header... | No, it's not the same as a regular function. With a regular function, you can declare
void foo(int);
void foo(double);
in a header, define the functions in some source file, such as foo.cc, #include the header in any source file that has to use those functions, such as bar.cc, and let the linker do the rest. The compi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.