question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,551,168 | 6,551,318 | Matching strings using Boost Spirit | I am learning Boost Spirit and simply modified an example given in the documentation to match strings instead of doubles. But the code doesn't compile and I get errors which I am unable to debug. Below is the code and the printed errors. Can you please help me debug this problem ?
PS: I am guessing the problem lies in ... | If you write it as
bool r = phrase_parse(
first, last, +(char_[push_back(ref(v), _1)]), char_('/')
);
it will work. But writing
bool r = phrase_parse(
first, last, +char_, '/', v
);
is even simpler (and runs faster).
|
6,551,213 | 6,551,237 | change bit size of packed struct in derived class | The existing code:
typedef unsigned int uint;
Class A
{
union xReg
{
uint allX;
struct
{
uint x3 : 9;
uint x2 : 9;
uint x1 : 14;
}__attribute__((__packed__)) __attribute__((aligned(4)));
};
};
My requirement:
Now, I need to deri... | You cannot change a bit-field length in a derived class in C++.
What you could try, however, is parametrize your class with the bit_field lengths.
template <size_t N1, size_t N2, size_t N3 = 32 - N1 - N2>
struct myStruct
{
uint bitField1 : N1;
uint bitField2 : N2;
uint bitField3 : N3;
};
Now you can instan... |
6,551,492 | 6,551,511 | How to distinguish between bind() in sys/sockets.h and std::bind? | I'm using g++ 4.6.0 to compile some C++ code that successfully compiled in earlier versions.
if ( bind(iControl, (struct sockaddr *) &sa, sizeof(sa)) == -1)
throw runtime_error ("bind");
where iControl is a socket, and sa is a struct sockaddr_in.
However, in g++ 4.6 I get the following error:
comms.cpp:93:66: error:... | Qualify it to be global: ::bind(...) (and make sure you have all the right headers included).
EDIT: (I got the idea from @Bo Persson's comment)
Another solid option is to change using namespace std; to several using <thing> like:
using std::cout;
using std::endl;
using std::string;
// etc.
This lets your old code comp... |
6,551,621 | 6,552,781 | Slow performance on x64 free | I have a class like this (assume all malloc's succeedes)
class CMyClass
{
public:
CMyClass()
{
lpData = malloc(128);
};
~CMyClass()
{
free(lpData);
};
public:
LPVOID lpData;
};
then I execute this:
CMyClass *lpList = new CMyClass[32768];
delete [] lpList;
The problem is that in x86 the code works... | It is possible that if you are running your test app through a debugger that you are hitting some performance issue with the Windows debug heap. Add _NO_DEBUG_HEAP=1 to the environment settings for the debuggee (in the Project Properties->Configuration Properties->Debugging->Environment property under Visual Studio 20x... |
6,551,787 | 6,551,807 | What is the scope of these variables? | Please see the C++ code fragment below:
#include .....
Class1 class1;
Class2 class2;
...
void Class3::foo() {
...
}
What are the variables: class1 and class2? Are they global variables? Static variables? What actually are these? In C++ OO programming, is it good practice to use these because any member funct... | Yes class1 & class2 are global variables.
What are global variables?
Variables declared outside of a block are called global variables. Global variables have program scope, which means they can be accessed everywhere in the program, and they are only destroyed when the program ends.
Because global variables have prog... |
6,552,141 | 6,553,169 | How can a stack underflow happen in C++? | What is a simple example in C++ that causes a stack underflow in the case of invoking and returning from method calls?
I am familiar with the calling convention, i.e thiscall, stdcall and the cdecl and way they would clean the stack. Wouldn't a stack underflow automatically be taken care of by the code generated by the... | The only way I can see this actually happening would be if you declared a function to use the stdcall (or any other calling convention that specifies the callee clean the stack) and then invoke the function through a function pointer that was specified as a cdecl (or any other calling convention where the stack is clea... |
6,552,261 | 6,552,491 | C++ cross platform build automation | I have a cross platform C++ project that targets and successfully compiles on Linux, OSX and Windows. I'm using GNU Make to handle the building on all platforms, gcc for compiling under Linux & OSX and cl.exe to compile under Cygwin on windows. My current workflow consists of coding under OSX and then building on each ... | If I understand the OP correctly, the question isn't about replacing make but how to launch the build on each platform?
I'd suggest using http://jenkins-ci.org/ - it's java and can be run on Windows, Linux, OSX, etc. It can be configured to launch build jobs concurrently so that any time you want to do a build each pla... |
6,552,285 | 6,552,646 | Overlapping source and destination blocks in memcpy with boost | Can anyone explain me why on that c++ simple code valgrind returns this.
First problem is with boost:regex. When i use subpattern with a question mark (for optional matching) valgrind will return:
Source and destination overlap in memcpy (line 8)
Second problem is with std::string::erase.
I have no idea what am i doing... | Seems like the library code is using memcpy when, to be strictly portable, it should be using memmove.
For the compiler's library, like std::string, this is probably ok as that code doesn't have to be portable to other compilers, and can use knowledge about how the specific implementation works.
With the boost library... |
6,552,319 | 6,552,329 | c++ sizeof() of a class with functions | I have a C++ question.
I wrote the following class:
class c
{
int f(int x, int y){ return x; }
};
the sizeof() of class c returns "1".
I I really don't understand why it returns 1.
Trying to understand better what is going on, I added another function:
class c
{
int f(int x, int y){ return x; }
int g(int... | The class contains no data members, so it's empty. The standard demands that every class have at least size 1, so that's what you get. (Member functions aren't physically "inside" a class, they're really just free functions with a hidden argument and a namespace and access control.)
|
6,552,361 | 6,566,809 | How to make the code flow without closing the VTK render window? | I'm using Visual Studio 2010, VTK 5.6 and configure my projects without using CMake.
I'm dealing with numerical computing and want to generate several plots during the runtime using VTK. Starting with the line plot example given in the VTK web page I managed to generate the plot that I want. The problem is that the cod... | If you just want to render the plot, do something else, update and render again you can skip the renderWindowInteractor code, and simply call
view->Render();
This will render the plot with the data you supplied, and control will return to your code. You can continue doing this and call Render() on the view whenever yo... |
6,552,362 | 6,620,908 | Gstreamer elements not appearing available in c program but they do appear available using gst-tools | I have a c++ program using gstreamer. The problem is that several of my elements--namely the ffmpeg plugins--do not work in the program. However when I run for example:
gst-inspect | grep ffenc_h261 It shows up.
If I run gst-launch .... ! ffenc_h261 ! ... , it works.
However in my application, I always receive eleme... | Turns out that my distro was all flubbed up. I uninstalled everything that uses gstreamer, sudo apt-get purge gstreamer*, then downloaded all of the source, compiled, and installed. It was a real pain in the ass, but I got it working. One more reason that most package managers are nice, but are no substitute for knowin... |
6,552,660 | 6,580,109 | C++ DBI Class - best/developer friendliest style | In our current project, we need some high level DBI for different databases. It should provide the following features:
in memory cache - the DBI should be able to cache all reads, and update the cache on writing calls (the application we are coding on is heavy threaded, and needs fast access to the current data all th... | How about using object relational mapping? Here's some code fragment ideas off the top of my head - I've only done this in Python, never in C++, and only for fairly simple databases. There's a list of frameworks on Wikipedia that should avoid too much wheel-related R&D.
class people: public dbi_table
{
// id column... |
6,552,689 | 6,552,818 | Real world example of dynamic_cast in C++ | Can anybody give me a real world example of a case when dynamic_cast is needed and can't be worked around at all? Examples I can think of can generally be worked around with double dispatch.
If the constraint is too strong, an example where dynamic_cast is generally the way to go would also be nice.
I'd like to see rea... | Double dispatch requires that the types that are interacting have intimate knowledge of each other's innards, as it requires that one class call methods on the other class. dynamic_cast works when you cannot modify the innards of a class, or do not wish to break encapsulation of the classes in question.
That is, double... |
6,552,876 | 6,561,367 | file stream tellg/tellp and gcc-4.6 is this a bug? | This code:
#include <iostream>
#include <cstdio>
#include <fstream>
#include <string>
int main()
{
std::remove("test.txt");
std::fstream f("test.txt",std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);
std::cout << f.good() << std::endl;
f<<"test"<< std::flush;
std::cout << f.tel... | Ok, it is not a bug, even it seems that it is required behavior:
According to C++ 2003 standard:
tellg(): (27.6.1.3)
After constructing a sentry object, if fail() != false, returns pos_type(-1) to indicate failure. Otherwise, returns rdbuf()->pubseekoff(0, cur, in).
sentry (27.6.1.1.2):
if noskipws is zero and is.... |
6,552,913 | 6,552,937 | what does - if(1, true) - mean? | I came across this code:
if (1, true) {/*...*/}
What does it actually mean?
While this evaluates to true:
void foo(){}
...
if(1, foo()) {/*...*/}
this doesnt compile:
void foo(){}
...
if (1 == foo()) {/*...*/}
obviously because compiler expects foo() to return some integral value. I thought that the comma translates... | The comma operator simply evaluates its left operand, followed by its right operand. So an expression like
(1, true)
evaluates the 1 first, then the true, resulting in an expression value of true.
In this particular case, the use of the comma operator seems rather pointless.
|
6,553,232 | 6,553,553 | How to tell TCL and TK that default `.tcl` language files should be searched locally? | When you compile TCL/Tk manually from sources or just install it from ActiveState you get the following structure in your TCL/Tk installation folder:
+- bin
+- tcl85.dll
+- tk85.dll
//...
+- lib/
+- tcl8.5/
//All TCL files (.tcl)
+- tk8.5/
//All TK files (.tcl)
... | If you have a directory that contains your binary, and you want to locate those Tcl files relative to it, like this:
yourapp1.0/
+- yourapp.exe
+- extras/
+- tcl/
+- foo.tcl
+- bar.tcl
+- tk/
+- grill.tk
Then you can write Tcl code to find those scripts. That code... |
6,553,282 | 6,554,476 | Is there a true 64-bit version of msvcr80.dll? If not, why not? | I have read the link that answers the question of whether there is a 64 bit version of Visual Studios ( Visual Studio 64 bit? ). The simple answer is No, but the 32 bit Visual Studio development environment can produce 64-bit executables.
Questions:
1) Is there a 64 bit version of the Microsoft redistributable libra... | Beyond Compare isn't using the PE headers for what it's displaying - it's using version resources, and the FILEOS version resource for the x64 msvcr80.dll has the value VOS_NT_WINDOWS32 (as far as I know there isn't a VOS_NT_WINDOWS64).
Use dumpbin /headers (or link /dump /headers) to get your information about the P... |
6,553,396 | 6,618,807 | C++ callback with python through SWIG when the function takes non-trivial arguments? | I just read the following section of the "SWIG and Python" tutorial:
http://www.swig.org/Doc1.1/HTML/Python.html#n11
I understand what they do in the example, basically you write a C function that calls python. However, the example provided takes only a double in the argument list, making it rather trivial to build an ... | I do not think your question is actually about SWIG; it is purely about Python. At this level, your problem is simply calling in to Python from C, so you need to study "Parsing arguments and building values" in the Python documentation. (Also "Extending and Embedding the Python interpreter".)
|
6,553,559 | 6,563,655 | How to use FeatureDetector in OpenCV C++? | I am using VS 2008 with OpenCV 2.1 installed as per the installation guide. FeatureDetector/SurfFeatureDetector are listed as classes in the documentation, but they are considered "syntax error : identifier 'SurfFeatureDetector"
This is pretty much the entirety of my code.
#include "cv.h"
#include "highgui.h"
Ptr<Feat... | I think you have installation problem, try resinstalling from here: sourceforge.net/projects/opencvlibrary/files/opencv-win/2.2
anther other option is that your precompiler already has __OPENCV_OLD_CV_H__ defined.
Try undefining it before #include "cv.h"
When you type #include "cv.h"
It automatically should include f... |
6,553,583 | 6,553,668 | C++ LPTSTR problem calling CreateProcessAsUser with getenv | I am trying to call function CreateProcessAsUser. Passing constant string is fine. Trying to pick up an Environment variable using char* getenv(const char name) is causing me a problem.
If I use the following, notepad.exe will run.
CreateProcessAsUser(hTokenDup, _T("c:\\windows\\notepad.exe"),
_T... | The third parameter, lpCommandLine is LPTSTR which means it must be writeable memory. You need to copy the command line into a writeable string before calling CreateProcessAsUser.
The documentation for getenv states:
It is not safe to modify the value of the environment variable using the returned pointer.
You there... |
6,553,734 | 6,553,843 | Derive & Destroy Encapsulation, or Violate DRY? | I have two C++ classes: Sequence, which is just like std::vector, and File, which is a Sequence of strings that represents a file on the machine.
Deriving File from Sequence is a no-brainer. Its behavior is exactly the same, but with the added functionality of reading and writing files. The File-specific functionalit... | Well, deriving Sequence from Array with public inheritance in your case is definitely bad idea (as deriving square from rectangle). In the terms of Object-Oriented Programming, Sequence IS NOT an Array, since Array has a property that Sequence does not have, and it's: An Array object cannot be resized. If you make a de... |
6,553,945 | 6,554,029 | C++ Some Stack questions | Let me start by saying that I have read this tutorial and have read this question. My questions are:
How big can the stack get ? Is it
processor/architecture/compiler
dependent ?
Is there a way to know exactly how
much memory is available to my
function/class stack and how much is
currently being used in order to
avo... |
Yes, the limit on the stack size varies, but if you care you're probably doing something wrong.
Generally no you can't get information about how much memory is available to your program. Even if you could obtain such information, it would usually be stale before you could use it.
If you share access to data across thr... |
6,553,975 | 6,554,042 | Embedding Python in C++ libraries | I'm working on embedding Python in some C++ code, but I'm getting stuck compiling it.
For a header file, I have
#include <Python.h>
I would initial try,
$g++ EmbeddedPython.cpp
but would end up getting
EmbeddedPython.cpp:1:20: error: Python.h: No such file or directory
EmbeddedPython.cpp: In function ‘int main(int, c... | You need to link against libpython. UNIX programmers do this with "-lpython" in the link command (ie at the end of that "g++" command). On a Mac, I think it would be "-framework Python".
|
6,554,120 | 6,554,131 | Will inline speed up void a(string b) { cout << b; } | For an assignment, we're supposed to write two methods for handling outputs. One for outputting strings, and one for integers.
Basically we have two methods calling another method:
void TheClass::displayString(string str){ cout << str; }
void TheClass::displayNumber(int n) { cout << n; }
Will inline speed things up by... | Namespaces don't have anything to do with it.
You probably won't see any benefit here for one simple reason: the function is so small that I'd expect the compiler to be inlining it anyway.
Remember, the keyword inline is a hint not a directive, and usually you can just let your toolchain decide when to inline. It's goo... |
6,554,373 | 6,554,424 | Low level C/C++ networking concepts for real-time programming? | I'm rather interested in real-time programming and whilst I feel I know a decent amount regarding algorithms and data structures, I dont feel I know much about how to get the data into the computer as quick as possible in order to process.
Would any of you be so kind as to point me to topics I could google for, in orde... | Just so you know: Real Time means that you have a time constraint on your application, it doesn't necessarily mean "fast" or "quick" or "efficient". Real-time operation can take 1 hour, but it will be real time as long as it is restricted to last no more than 1 hour.
As to the networking - it by itself is not real time... |
6,554,492 | 6,555,232 | error: Class has not been declared despite header inclusion, and the code compiling fine elsewhere | So I have a class included in another class that keeps throwing a compile error of the form "error: 'ProblemClass' has not been declared. The files are set up thusly:
#ifndef PROBLEMCLASS_H
#define PROBLEMCLASS_H
#include <iostream>
#include <cmath>
class ProblemClass
{
public:
virtual void Init() = 0;
};
#en... | You seem to be saying that the code you are showing doesn't actually produce the compiler error that you are having a problem with. So we can only guess. Here are some possibilities:
You could have forgot to include problemclass.h from the file where you are using ProblemClass.
You could have misspelled the name of Pr... |
6,554,771 | 6,554,795 | OpenGL/GLUT keyboard managed with bool*: all values appear to be set to ints at second initialisation. Any ideas? | Making a game with OpenGL/GLUT and C++.
I've heard the easiest way to manage keyboard stuff in GLUT is to use an array of bools.
So basically, here's what I have:
bool* keys = new bool[256];
...
void keyDown(unsigned char ch, int x, int y)
{
keys[ch] = true;
}
void keyUp(unsigned char ch, int x, int y)
{
... | This statement
keys = new bool[256];
Allocates memory. It does not initialize that memory to any particular value. To do that, you could do a memset(keys, 0, sizeof(bool) * 256) to zero.
However, you shouldn't allocate memory (which is what new does) to reinitialize an array. You should actually reinitialize it, using... |
6,555,015 | 6,555,104 | Check for invalid UTF8 | I am converting from UTF8 format to actual value in hex. However there are some invalid sequences of bytes that I need to catch. Is there a quick way to check if a character doesn't belong in UTF8 in C++?
| Follow the tables in the Unicode standard, chapter 3. (I used the Unicode 5.1.0 version of the chapter (p103); it was Table 3-7 on p94 of the Unicode 6.0.0 version, and was on p95 in the Unicode 6.3 version — and it is on p125 of the Unicode 8.0.0 version.)
Bytes 0xC0, 0xC1, and 0xF5..0xFF cannot appear in valid UTF-8.... |
6,555,098 | 6,555,127 | How do I add custom windows' resources into executable without resource compiler? | I was able to load a bitmap object (LoadImage) into executable (and implement it as an icon); however, when I release it as a standalone executable, the icon disappears. I found out that it requires the bitmap to be present in directory at runtime for this trick to work. However, my executable desktop icon will not cha... | You could use BeginUpdateResource, UpdateResource, and EndUpdateResource to add the bitmap resource to your executable as post-build step or something, but why avoid using the resource compiler? It's really much easier, more straightforward, and future-proof than hacking your own solution.
|
6,555,107 | 6,742,258 | Win32 API used to get active directory tickets? | Does anyone know the Win32 API used to get active directory(kerberos) tickets?
Based on this question my understanding is that the SQL Server driver uses the Win32 API to get TGT tokens from the local OS instance. (Providing trusted connections)
Does anyone know what this API is and the doco and examples for using it?... | Previous to the change that is described in the "Summary" section of this article, programs could use the Win32 LsaCallAuthenticationPackage API specifying KERB_RETRIEVE_TICKET_REQUEST and either KerbRetrieveEncodedTicketMessage or KerbRetrieveTicketMessage message types to retrieve a Kerberos ticket-granting-ticket (T... |
6,555,432 | 6,555,478 | Converting a simple folder to shared folder in Qt C++ | I just made a program in Qt that creates a folder in a specific diretory.
the code is:
QDir directory;
directory.mkdir("Sample");
my problem is how could i convert the folder to a shared folder using Qt codes?
Or is there a way to create a shared folder using Qt??
| You can share a directory using NetShareAdd. As far as I know, Qt doesn't provide anything with the same basic capability as NetShareAdd.
Edit: here's a quite bit of demo code:
#include <windows.h>
#include <lm.h>
int main() {
SHARE_INFO_2 info = {0};
info.shi2_netname = L"test_share";
info.shi2_type = ... |
6,555,492 | 6,561,965 | launch error: using eclipse cdt with visual c compiler error(cl.exe) | I try to using eclipse 3.7 cdt with visual c++ compiler to compile my cpp code appling default setting.
the compile and link process are ok. But the program still could not launch with an error.
"A program file was not specified in the launch configuration."
| See this IBM article (about the debug configuration, but also useful for a "run" configuration):
You need to specify the Project and executable to run.
|
6,555,515 | 6,555,599 | Why base class is not automatically deduced in the same "auto" declaration? | Below error related to auto, is understandable:
auto i = int(), d = double(); // error: inconsistent deduction for ‘auto’
However, why following is victimized with the same error:
struct B {};
struct D : B {};
const auto &b1 = B(), &b2 = D(); // error: inconsistent deduction for ‘auto’
Having known that, b1 is alrea... | The danger would be unexpected results... when you create a D, you expect to get a D as the result. There is also the fact that there is a cast involved... it is a "safe" cast, but a cast none-the-less. An identical argument could be made for the first example... why doesn't the compiler just make d and int, since do... |
6,555,732 | 6,555,860 | How do I include header file | I have a packet class and a packetfactory class.
In packet factory class it includes packet.h file and in packet class it includes packetfacotry.h file.
Then I am getting an error "packet does not name a type " in packetfactory.h file.
How do I fix this?
Thanks in advance.
| 2 ways :
First, you can #include "packet.h" in packetfacotry and #include "packetfacotry.h". DO NOT forget to protect your headers.
Second, if you have an circular inclusion juste add class packet; in your "packetfacotry.h. file or vice versa.
It declares symbols for preprocessor.
So ?
|
6,555,826 | 6,555,871 | Argument deduction for template member functions does not work for classes declared inside function? | struct Test
{
template <class T>
void print(T& t)
{
t.print();
}
};
struct A
{
void print() {printf( "A");}
};
struct B
{
void print() {printf( "B");}
};
void test_it()
{
A a;
B b;
Test t;
t.print(a);
t.print(b);
}
This compiles fine.
struct Test
{
... | In your second example, A and B are local types, which can't be used as template type arguments in C++03 as per §14.3.1/2:
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
|
6,555,866 | 6,555,928 | Unencapsulated means Unchangeable? | I came across this line in Effective C++:
Public means unencapsulated, and practically speaking, unencapsulated means unchangeable, especially
for classes that are widely used.Yet widely used classes are most in need of encapsulation, because
they are the ones that can most benefit from the ability to replace one ... | The general idea is simple. If you make something public, then someone can and probably will use it. Therefore, if you change something that is public, all of the code that uses it immediately breaks. Breaking people's code is bad; it tends to lead to them not wanting to use your code anymore, since now you've forced t... |
6,556,113 | 6,556,168 | UDP Tx loop stops working every time at exactly 3970 packets, 14386 on my friends computer | I've been stuck at this issue for the last 4 days and I can't seem to figure it out. I'm trying to send data to myself using UDP packets so another program can read the bytes.
I can clearly read the packets but I only get up to 3970 before the UDP portion of the program hangs. Glut and everything else continues to run ... | You are allocating new sockets in a loop (the first argument to sendto), you are also allocating another for bind, but these are never freed. You eventually run out of socket handles to allocate, hence your program hanging.
Instead, allocate a socket once in SUDP_init, store it instead of discarding it, then pass that ... |
6,556,413 | 6,556,428 | Why is it OK to return an object reference inside a function in c++? | Here is an example from website: http://www.cplusplus.com/doc/tutorial/classes2/
I know it is a working example. However, I don't understand why object temp can be returned from the operator+ overloading function. I have made some comments besides the codes.
// vectors: overloading operators example
#include <iostream... | In your example you don't return an object reference, you simply return the object by value.
Object temp is in fact destroyed after the function exits but by that time its value is copied on the stack.
|
6,556,430 | 6,556,453 | Template specialization for types providing a traits class | I have a class
template <typename T> struct Dispatch;
which is used to call a type-specific function. For instance, assume I have dispatchers like
template <> struct Dispatch <MyClass> {
static void Apply (void* a, MyClass& m)
{
::memcpy (a, &m, sizeof (m));
}
};
Now I have a bunch of classes for which I ... | Use boost enable_if.
If boost is unavailable, check out the enable_if idiom.
|
6,556,449 | 6,556,492 | Error message: name lookup of ‘jj’ changed for ISO ‘for’ scoping, (if you use ‘-fpermissive’ G++ will accept your code) | The error is:
In function ‘int returnShortestWeightedBranch(std::vector<route, std::allocator<route> >*)’:
error: name lookup of ‘jj’ changed for ISO ‘for’ scoping
note: (if you use ‘-fpermissive’ G++ will accept your code)
The code is:
for (int i = 0; i< routeVector.size(); i++)
{
if (routeVector[... | You have a semicolon at the end of the inner for statement. That ends the scope of jj there, so it is not visible inside the block.
Edit
You have solved the scope problem, but still have your for loop executing just
<nothing>;
Remove the semicolon after the parenthesis!
|
6,556,924 | 6,556,946 | Difference between WNetAddConnection2() and NetUseAdd() | I'm mounting a remote drive locally (see User/password problems with GetVolumeNameForVolumeMountPoint() (Windows remote drive mount?))
QUESTION: What is the difference between WNetAddConnection2() and NetUseAdd()? It appears they each permit you to assign a remote drive path to a local drive letter providing username... | NetUseAdd() makes the connection visible in Windows Explorer, while WNetUseConnection() and WNetAddConnection() do not make the connection visible in Windows Explorer.
|
6,556,978 | 6,556,999 | c++ generic to_stream() and from_stream() | I wonder if the following works (I guess not, otherwise everyone would've used it, right? :-)). I tried them on simply classes I wrote, but I wonder if it works for the general case. One can write a to_stream() function for a generic class by simply copying the memory of the object to CHAR[]?
For instance:
memcpy(buf,... | As explained in an answer to this question, you will do no good in treating objects as if they were raw bytes. This will work for aggregate types / POD types, but if you got but a virtual function or a pointer/reference in that class, you're f*cked.
|
6,557,042 | 6,577,036 | How to disable a particular unknown #pragma warning (GCC and/or Clang) | I know how to disable all unknown #pragma warnings. The answer was given, for example, in How can I disable #pragma warnings?.
Is there a way to disable an 'unknown pragma' warning for one particular pragma? For example, if I disable warning for #pragma ugubugu the following code:
#pragma ugubugu
#pragma untiunti
int ... | I'm reasonably sure that there isn't any way to do this.
Both GCC and Clang do have internal interfaces which allow the language frontend to register #pragma handlers with the preprocessor - see GCC's libcpp/directives.c and Clang's lib/Lex/Pragma.cpp - but, as far as I can see, there is nothing which lets you modify w... |
6,557,158 | 6,557,217 | Is deleting an element in the middle of a std::vector still expensive with movable types? | It is generally thought of deleting an element in the middle of a std::vector to be costly, as it needs to copy every element after it down to fill the hole.
With C++11, std::vector will instead move all the elements down, which should be very fast (if only in relation to the copy), atleast I think so. It will still b... | If you take into account what the standard uses for cost, it will be exactly as costly. The standard states the costs in terms of operations performed on the contained type, and that number of operations is still the same, it is just that each one of them will be faster.
As an example, consider in C++03 the cost of ins... |
6,557,300 | 6,557,308 | shared_ptr from pointer | I have a class which can't be created on heap and it has private destructor.
But there is a function which returns a pointer to such constructed object. I want to make a shared pointer from it:
MyClass *GetMyClassPointer() {...}
boost::shared_ptr<MyClass> ptr;
ptr = boost::shared_ptr<MyClass>(GetMyClassPointer()); // ... | Yes.
It sounds like the instance is being dynamically allocated by a function which has access to the private constructor (either member or friend). Then there should be a public function for cleaning up the instance when you're done with it, which has access to the private destructor (even though you don't).
Use the ... |
6,557,565 | 6,560,390 | Using decltype with member function pointers | I have some trouble using decltype for member function pointers:
#include <iostream>
#include <type_traits>
struct A
{
void func1() {}
typedef decltype(&A::func1) type;
};
int wmain(int argc, wchar_t* argv[])
{
typedef decltype(&A::func1) type;
//Case 1
std::wcout
<< std::boolalpha
... | For the sake of formality (having an answer to the question), this appears to be a bug in VC2010's compiler. File a bug report so that Microsoft can fix it in the next version.
|
6,557,594 | 6,557,607 | C++ Template: What happens if we put wrong thing in our template class | C++ templates allow we put whatever in our objects with template arguments. However, if our template arguments use functions/variables which belong to certain types, how do we check?
template<typename BarType>rguments
class Foo {
public:
Foo() { bar = new BarType() }
private:
BarType * bar;
}
Foo<Bar> ... | You will get a compile-time error if your templated code makes reference to members that the actual parameter doesn't provide when you try to instantiate the template. So don't worry, you won't be able to break anything.
Think of templates as a code-generation mechanism. Whether the generated code actually makes sense ... |
6,557,656 | 6,557,706 | multithreaded linked list in C++ | First a little explanation of what I am trying to do:
My plan is to write a program with a socket stream implemented using the boost::asio library which feeds data to a parser implemented using boost:spirit::qi. The parser will take the packets and fill a packet object and then append that object to the end of a linke... | Check this article, it's about multiple consumers, but still brillant:
Measuring Parallel Performance: Optimizing a Concurrent Queue
|
6,557,768 | 6,558,306 | Thread-Local storage and iOS | My understanding is that iOS does not support __thread. There is, obviously, a way to do this using pthread_setspecific. However, is there already a template class that has implemented this functionality?
I'd ate to re-invent the wheel, especially as it won't be a simple piece of code to write.
Any links would be hug... | Foundation provides -[NSThread threadDictionary]. You can use this to store thread-local Objective-C objects, which could include an NSValue wrapping the address of any dynamic storage.
Note that Cocoa is moving towards thread-blind execution of threaded code, where you submit blocks of code to be run on any available ... |
6,557,826 | 6,560,018 | Exceptions when reading protobuf messages in Java | I am using protobuf now for some weeks, but I still keep getting exceptions when parsing protobuf messages in Java.
I use C++ to create my protobuf messages and send them with boost sockets to a server socket where the Java client ist listening. The C++ code for transmitting the message is this:
boost::asio::streambuf... | I am not familiar with the Java API, but I wonder how Java deals with an uint32 value denoting the message length, because Java only has signed 32-bit integers. A quick look at the Java API reference told me an unsigned 32-bit value is stored within a signed 32-bit variable. So how is the case handled where an unsigned... |
6,558,132 | 6,558,501 | Embed XNA in WinForms | Is it possible to embed an XNA game in a C# WinForm or a C++ Window. If yes then How.
I want to use normal UI controls & have a windowed interface of the game for more interactive & dynamic simulations.
| The official samples:
XNA WinForms Series 1: Graphics Device
XNA WinForms Series 2: Content Loading
|
6,558,240 | 6,558,265 | Data structure for sorting/retrieval strings | I have multiple arrays of strings, I used a comparison function to sort them in a priority queue. I overlooked the fact that I need to iterate through the strings..
What other data structure would you recommend? Perhaps something that allows a comparison function so that I get a sorted set of strings
I could effectivel... | A set would work, but you could just make a vector, reserve enough capacity, and then use sorted inserts using lower_bound. Since strings are cheap to swap, this should be fine (and in any case 450 is a tiny number).
A vector has constant-time lookup and random access, so if you don't need to insert and erase a lot, it... |
6,558,633 | 6,558,714 | "template polymorphism" when calling function for templated parameter of base type, with derived type? | I've got a template class:
template <class T>
class TemplateClass
{
//irrelevant what this class does
}
And two classes, one base and one class which derives from it:
class Base
{
//does whatever
}
class Derived : public Base
{
}
Now I want to assemble a function which can deal with TemplateClass of templated... | Sadly, C++ does not support template covariance, so you cannot do that automatically. As a workaround, you could do something like this:
template <typename T>
void DoSomething(const TemplateClass<T*>& tc) {
// in C++03, use BOOST_STATIC_ASSERT and boost::is_convertible
static_assert(
std::is_convertible... |
6,558,697 | 8,461,858 | C++ map: expected initializer before ‘<’ token | I'm getting this error in a header file:
error: expected initializer before ‘<’ token
class MyEntity;
typedef std::map<uint16,MyEntity*> myList_t;
I figured it's not seeing the map include, but at the top of that header file is:
#include <list>
#include <map>
In another header file:
typedef unsigned int ... | There was a macro named map that was causing a conflict.
|
6,558,942 | 6,558,994 | How do I write a Cairo surface to png to stdout? | I'm trying to write a CGI program that will output a PNG image to stdout. I can already do this from an image file (PNG or otherwise), but now I'm using Cairo to dynamically generate some image, then output it to the browser.
The problem I'm facing is this: the way Cairo writes a surface to a PNG is using one of two fu... | As it says in the documentation, write a function to handle the writing:
#include <cstdio> // for stdout
Cairo::ErrorStatus my_write_func(unsigned char* data, unsigned int length)
{
return length == std::fwrite(data, length, stdout) ? CAIRO_STATUS_SUCCESS : CAIRO_STATUS_WRITE_ERROR;
}
Usage:
my_surface.write_to_png... |
6,559,064 | 6,559,088 | when you push_back heap-allocated char into a vector in c++ | I'm having trouble inserting char* into a vector< char*>
When I do the following:
string str = "Hello b World d"
char *cstr, *p;
vector<char*> redn;
cstr = new char [ (str.size)+1 ];
strcpy(cstr, str.c_str());
//here I tokenize "Hello b World d"
p = strtok(cstr," ");
while(p!=NULL){
redn.push_back(p);
cout <... | What is wrong in your code?
Other answers explain you how to do it in a better way. My answer explains why your code doesn't work as you expected it to and a quick fix to get it working.
With the statement:
delete[] cstr;
You delete the string after you push the object in to the vector, this causes your vector element... |
6,559,622 | 6,559,891 | Template specialization for char pointer? | boost::lexical_cast is a great tool but in my application I ran into a limitation in string -> bool conversion that is bugging me. I need to convert all strings like "0", "false" and "FALSE" into false and "1", "true" and "TRUE" into true.
boost::lexical_cast only support conversion from/to "0" and "1". So my idea was ... | Here is a solution that works. I got the idea from boost::lexical_cast itself:
template<class T>
struct array_to_pointer_decay
{
typedef T type;
};
template<class T, std::size_t N>
struct array_to_pointer_decay<T[N]>
{
typedef const T * type;
};
template<typename Target, typename Source>
Target my_cast_intern... |
6,559,661 | 7,719,471 | XCode assistant editor doesn't show my .h and my related .cpp file | If I create .cpp file from xcode, it will create .h file for me automatically, and I will be able to view two files together in Assistant Editor. It will show .h file relate to .cpp file right next to each other.
However, I create my project from TextMate and import those files manually. Now, when I click .h file it w... | Hmmm.. I tried to recreate your problem, but it worked for me.
I have two thoughts:
1) Are you sure they are named the same thing? If not, it doesn't seem to consider them counterparts.
2) When you've switched to the Assistant Editor, to the right of the back/forward buttons is a dropdown menu to select which file to d... |
6,559,771 | 6,559,781 | Suspend module with module handle | I'm looking for a way to suspend a module with only the module handle. Alternatively is there a way I can grab the main thread handle with the module handle? I am still quite new to C++ so I'm not sure if this is possible.
| You can't suspend modules. You can suspend threads although you should not do so. A module does not have a main thread. A process has a main thread.
Suspending a thread is not something that should be done in
a forceful way. Doing so leads to deadlocks. You should instead signal the thread to pause and then wait until ... |
6,559,848 | 6,560,075 | Doubt with the template instantiation problem in the below snippet of a user defined class | Couldn't find anything relevant in forums So ,Please help me with this code .I'm brushing up my c++ concepts and met with a strange error
#include<iostream>
using namespace std ;
class base
{
int i ;
public:
virtual void f(){cout<<"base" ; return ;};
};
class derived: public base
{
int j ;
public:
void f()... | base is not a complete derived type, so you'll have to provide a constructor inside your template that fills in the missing details.
template<class T> //original template
class test
{
public:
test(T b)
{
b.f();
cout<<endl<<" "<<sizeof(b)<<endl;
}
};
When you create an instance of this templat... |
6,560,083 | 6,560,102 | C++ vectors, sorting and custom class operators | I am puzzled because I cannot figure where my bug/problem is.
I have a class Instruction, which uses two custom operators, one assignment and one comparison operator.
Previously I only used the comparison operator in order to use std::sort to sort Instructions based on one of their members, an std::string name.
However... | Don't forget the rule of threes: if you have one of a copy construct, copy assignment operator, and destructor, then you should have all of them.
However, your copy assignment operator is effectively an infinite loop; it calls itself. Operator= will be used whenever you have anything of the form: Instruction &=Instruct... |
6,560,196 | 6,560,213 | Is is possible to pass a QString to a QMessageBox? | I'm working on QT application where the user will enter their information into several QLineEdits. They then will click son a Submit button. I would like a QMessageBox to appear asking if they would like to confirm their information(OK) or cancel. I want the messagebox to show the information they entered so that they ... | You should read a proper book on C++. For this, you just need to pass the string as the argument, translating is probably not what you want to happen, and & is just a syntax error:
QMessageBox::question(
this, tr("Confirm"), infoStr, QMessageBox::Ok | QMessageBox::Cancel
);
|
6,560,208 | 6,560,292 | Boost asio async_read (async_write) wrapper | I'm trying to code a wrapper over a boost::asio::ip::tcp::socket
Something like that :
class Socket {
public:
void async_read(AsyncReadStream & s,
const boost::asio::MutableBufferSequence & buffers,
CompletionCondition completion_condition,
... | Your main requirements seems to be "use SSL and non-SSL streams seamlessly." To do that, you can wrap a the various stream types in a way that exposes the functions you need to use.
Part of how you do that is deciding how you're going to do memory management. MutableBufferSequence is not a type, it defines a set of req... |
6,560,476 | 6,560,559 | Printing Objects via "<<" in a Linked-List in C++ | For an assignment (and for myself) I need to be able to print a singlely linked list of "Stock" objects.
Each Stock as the following private data members:
1 int
1 string
This is my print function in the linked list class I had to use/develop. I am not allowed to use STL::list().
//list.h
template<class NODETYPE>
void L... | If I understood your code, you'll have to overload the << operator to both ListNode and List classes.
//Representation of ListNode
template <class T>
ostream& operator << (ostream& ostr, ListNode<T>& ls) {
return ostr << "Foo"; //replace "Foo" with the proper representation
}
//Representation of List
template <cla... |
6,560,539 | 6,560,558 | Efficent way of swapping bytes in a memory-mapped file | I managed to parse a large binary file (~8Gb) by reading blocks of data into memory and swapping the big-endian integers by using the functions showed below. However, I am trying to gain more performance by using Boost Memory-Mapped files but I am not able to use the endian_swap functions because the file is opened wit... | At least the underlying operating system supports your desired behavior:
MAP_PRIVATE
Create a private copy-on-write mapping. Updates
to the mapping are not visible to other processes
mapping the same file, and are not carried through
to the underlying file. I... |
6,560,590 | 6,560,748 | is_function_pointer<> for <type_traits> | There are these in <type_traits>:
is_pointer<>
is_function<>
is_member_function_pointer<>
But not this:
is_function_pointer<>
Why is it so?
| The traits in [meta.unary.cat] are intended to classify each type into a single category. Is it a void, integral, pointer, etc. At this level, pointer-to-function is no different than pointer-to-int. And note that a pointer to a member is not a pointer. It is merely an english homonym.
It was intended that every ty... |
6,560,606 | 6,561,833 | On what architectures is calculating invalid pointers unsafe? | int* a = new int[5] - 1;
This line by itself invokes undefined behavior according to the C++ standard because a is an invalid pointer and not one-past-the-end. At the same time this is a zero overhead way of making a 1-based array (first element is a[1]) which I need for a project of mine.
I'm wondering if this is som... | The hardware for doing the checks is present in all x86 processors, we are just not using it at the moment in the most popular operating systems.
If you use a segmented memory architecture, which we did for 16-bit systems, an allocation is not unlikely to return the address segment:0. In that case you just cannot subtr... |
6,560,619 | 6,648,997 | C++ Why can't the linker see my files? | Building a native module for Node.js under Cygwin / Windows:
I have a monkey.cc file with this:
#include <monkey/monkey.h>
running
node-waf configure build
I get the following
'configure' finished successfully (0.351s)
Waf: Entering directory `/usr/src/build'
[2/2] cxx_link: build/default/monkey_1.o -> build/default... | Add monkey.lib='crypto' in the wscript.
|
6,560,625 | 6,560,653 | very basic C++ program closes after user input for no particular reason? | I just started learning C++ and I wrote this sample program from the text and when I compile and run it, it just closes after the user inputs any number and presses enter. I'm guessing the answer to this is very obvious so forgive me as newbie here....it's really my first C++ program :P
#include <iostream>
using n... | Imagine you were designing a model for application execution. You have two choices:
A) When the end of a program is reached it shall terminate.
B) When the end of a program is reached the program shall remain alive in some strange limbo state. It will still retain system resources and will not actually be doing anyth... |
6,560,736 | 6,560,767 | C++ conversion operators | I know the deal .The compiler tries to convert one object into the other objects's type with the help of conversion operator .Two ways to do this .Constructor (Converts a class to the other) or conversion operator .So , this one is just to test if I am thorough with the concepts .The code below gives the error
using n... | In these two lines you are telling the compiler to construct an A object with the default constructor, then call its nonexistent operator () (int) and return its return value:
A c ;
return c(this->i+b.i);
Use either
A c(i + b.i);
return c;
or
return A(i + b.i);
On a side note, an exam... |
6,560,760 | 6,560,847 | How do I link Allegro 5 from my Makefile? | I need to link the Allegro Game Development Library from my Makefile. When I do this, the compiler returns:
Undefinied Reference < Function Name >.
| Before trying to embed the compilation line into the Makefile, make sure you understand how to do it the command line, and more important, make sure it works:
g++ hello.cpp -o hello -I/usr/include/allegro5 -L/usr/lib -lallegro
Then, a simple Makefile to compile hello.cpp could be:
CXX=g++
CFLAGS=
LDFLAGS=-L/usr/lib -l... |
6,560,908 | 6,560,925 | Going mad trying to compile against OpenSSL/libcrypto | I have been trying to do this for nearly 3 days now. Its driving me nuts.
As you can imagine I'm quite new to C++.
Can anyone give me step by step instructions to do a hello world program making use of a function in openssl and compile it from a cygwin shell on Windows.
| You forgot to link with libcrypto. Append -lcrypto to your linker flags.
|
6,560,922 | 6,560,941 | Why must we do template <class/typename> T instead of just template T | Instead of
template <typename T>
void func(T arg) {/* something */}
why can't we do
template <T>
void func(T arg) {/* something */}
From cplusplus.com :
The only difference between both
prototypes is the use of either the
keyword class or the keyword typename.
Its use is indistinct, since both
expressions ha... | http://www.cplusplus.com/doc/tutorial/templates/ See the section on Non-type parameters for templates.
You need some keyword to distinguish type-parameters from non-type parameters.
template <class T, int N>
class mysequence {
T memblock [N];
public:
void setmember (int x, T value);
T getmember (int x);
}... |
6,560,975 | 6,561,014 | How do I read X file into RAM as a number in C++ in a linux environment? | I'm working on a compression program which needs to read a file into RAM as a single number and perform basic math operations and bit shifting. I've looked at gmp from GNU, but that has such poor integration into c/c++ I have no idea where to begin to read and put the values into the mpz_t variable.
| #include <fstream>
#include <gmp.h>
#include <gmpxx.h>
#include <iostream>
using namespace std;
mpz_class fileToNumber (const string& fileName)
{
mpz_class number;
ifstream file(fileName.c_str());
while( file.good() ){
unsigned char c;
file >> c;
number <<= 8;
number += c;
... |
6,561,005 | 6,561,375 | Output of cuda program is not what was expected | #include<cuda_runtime.h>
#include<stdio.h>
#include<cuda.h>
#include<stdlib.h>
__global__ void setVal(char **c){
c[(blockIdx.y * gridDim.x) + blockIdx.x] = "hello\0";
}
int main(){
char **gpu = NULL;
cudaMalloc((void**)&gpu, 6 * sizeof(char *));
int i;
/*
I cannot access second level directly
for( i =0 ; i < 6 ;... | Try this -- I tested it on a GTX 285 under CUDA 3.2 -- so it's a bit more restrictive than the current version, but it works.
#include<stdio.h>
#include<string.h>
__global__ void setValues(char** word)
{
volatile char* myWord = word[blockIdx.x];
myWord[0] = 'H';
myWord[1] = 'o';
myWord[2] = 'l';
m... |
6,561,134 | 6,561,158 | error C2064: term does not evaluate to a function taking 0 arguments | everyone!
I maintain a group of channel data in a map container, from which an individual channel data can be accessed by its channle name. With regards to this, I write a simple function GetIRChannelData (please see the following code). When compliing, the statement pusIRChannelData = cit->second(); throwed an error, ... | The error message is pretty clear... you call a function that doesn't exist. map::iterator points to a std::pair, which has two member objects, first and second. Note that these are not functions. Remove the () from the line in question and the error should go away.
|
6,561,212 | 6,561,255 | What are the use cases of not declaring the name for a typename in template? | Sometimes I see below kind of declaration:
template<typename> // <-- not "typename T"
struct A { ... };
What are the use-cases for such declaration. Are those useful or just a matter of style ?
| Did you really see that use for a template definition, and not for, say, a template declaration (only)?
Some uses:
// declaration only: the parameter name has no use beyond documentation
template<typename>
struct A;
// this is fine
template<typename T>
void eat_an_a(A<T> a);
// later, we can name the parameter to use... |
6,561,245 | 6,561,259 | How many parameters can I pass by reference in C++, without getting abnormal behavior | I had a problem with a function:
int parsearRestricciones(char linea[], unsigned int& x, unsigned int& y, unsigned int& tiempo, char restric[])
Inside that function I parse linea[].
The input consists in: three unsigned integers, and a string of punctuation characters. I need to read them that way.
The problem ocurrs ... | How many parameters can I pass by reference in C++, without getting abnormal behavior?
As many as you want to!
|
6,561,266 | 6,561,277 | Different ways of leaking memory | The basic concept of memory leaking is a mismatch of a new/delete operation during code execution, either due to wrong coding practices or either in cases of errors when the delete operation is skipped.
But recently I was asked a question in an interview about other ways in which memory can leak.
I had no answer to it.... | Common dynamic memory problems are:
Dynamic memory allocation with new and not deallocating with delete.
Dynamic memory allocation with new[] and deallocating with delete.
Dynamic memory allocation new and deallocate it with free.
Dynamic memory allocation malloc and deallocate it with delete.
In addition to ... |
6,561,322 | 6,561,397 | C++ making Hash of Arrays | I have a problem with the creation of a hash of arrays. I need a Single Key - Multi Data system:
multimap <Type, vector<type> > var;
But how I can add elements to the vector?
Example: key = 3;
Now I need to append some elements into the vector whose key is 3.
Creating a temp-vector not an answer because I don't know w... | To find the answer to your question you can look at the slides under point 6. at this site https://ece.uwaterloo.ca/~ece250/Lectures/Slides/
Hope that helps!
|
6,561,363 | 6,561,394 | Accessing a certain address in memory | Why can we access to a certain place in our memory in O(1)?
| That depends on the computing model that you use, in the Turing machine model, neither operation is O(1), in the random access model, access is O(1), which, since that is the case for most modern hardware using RAM makes that model useful. I assume you are using a model that for the sake of simplicity also allows O(1) ... |
6,561,417 | 6,565,158 | How do you copy/paste image data? | Using C++ and the WinAPI, how do I copy the image data from a pre-loaded image into the clipboard?
| You need to create an object that implements IDataObject, and then place it on the clipboard using OleSetClipboard.
When you place data in the clipboard you have the ability to specify multiple formats. This is so that the application reading the clipboard can enumerate the formats and decide which one to use.
There a... |
6,561,429 | 6,561,476 | Calling virtual function of derived class from base class constructor? | I´m trying to accomplish the same which is described in a previous question:
virtual function call from base class
But, my real question is:
What if f() is the constructor in the Base class? Which g() will be called? I don´t know if I am doing wrong, but in my program it seems to be that is the opposite.
Taking the sam... | Even though it's a virtual function, the base's version will get called since the derived class isn't fully constructed yet. The base class constructor is called before the derived class constructor, so if the derived virtual function were to get called, it would be with an incompletely-initialized instance - a possibl... |
6,561,520 | 6,571,328 | responsively checking two queues without pegging CPU | I have a thread pool system which uses message passing to organize events, and I am also using the Windows API which also does a bit of message passing. So essentially I need to use the functions which check for the presence of messages without blocking. If I block (if I use GetMessage I think it will block) while chec... | Normally, a thread pool would not be involved in the Windows message loop, and blocking indefinitely when there is no work is not only allowable for a worker thread, but even desirable.
The most elegant way of implementing a thread pool that can receive messages via some kind of queue, which automatically keeps all CPU... |
6,561,567 | 6,561,591 | How do I access objects in a linked-list in C++ | I'm very use to working with arrays and vectors, but now I'm playing with some STD::lists, as well as a custom list class I made.
Let's say I have a simple class, Stock.
//stock.h
class Stock{
public:
Stock(); //default constructor
Stock(string, double); //overloaded constructor
void setSymbol(string); //se... | for(int i= portfolio.begin(); i <portfolio.size(); i++)
If this worked for a std::vector, it was only by sheer accident. I have no idea how that might have worked for a vector.
std::any_stl_container::begin() returns an object called an "iterator". Specifically, an object of type std::any_stl_container::iterator. An i... |
6,561,604 | 6,859,593 | Mirroring the Y axis in SFML | Hey so I'm integrating box2d and SFML, and box2D has the same odd, mirrored Y-axis coordinate system as SFML, meaning everything is rendered upside down. Is there some kind of function or short amount of code I can put that simply mirrors the window's render contents?
I'm thinking I can put something in sf::view to hel... | I don't know what is box2d but when I wanted to flip Y axis using openGL, I just applied negative scaling factor to projection matrix, like:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glScalef(1.0f, -1.0f, 1.0f);
If you want to do it independent of openGL simply apply a sf::View with a negative x value.
|
6,561,643 | 6,561,693 | Boost Variant: How to model JSON? | I'm trying to parse JSON string using Boost Spirit store JSON object into recursive data structures:
Value <== [null, bool, long, double, std::string, Array, Object];
Array <== [Value, Value, Value, ...];
Object <== ["name1": Value, "name2": Value, ...];
And here's my code:
#include <map>
#include <vector>
#include <s... | You have to use a recursive wrapper (and you shouldn't be deriving from boost::variant):
struct JsonValue;
typedef boost::variant</*types*/, boost::recursive_wrapper<JsonValue> > JsonDataValue;
struct JsonValue
{
JsonDataValue value;
};
To make Boost.Spirit take a JsonValue, you will need to write one of those F... |
6,562,189 | 6,562,266 | Can you solve this circular dependency problem in C++? | There is an Object class with a clone() function that can throw a CloneNotSupportedException* and is declared such. CloneNotSupportedException derives from Exception, which derives from Object.
Inheritance requires complete types, and we have two of them, so it's obvious we can't break the circular dependency there. Me... | Skip the exception specification, it's worthless.
class Object {
virtual Object* clone() = 0;
virtual ~Object() {}
};
Done.
By the way, your design sounds so utterly wrong, I can't bring myself to not comment on it.
|
6,562,257 | 6,562,346 | Separate physics thread without locks | I have a classic physics-thread vs. graphics-thread problem:
Say I'm running one thread for the physics update and one thread for rendering.
In the physics thread (pseudo-code):
while(true)
{
foreach object in simulation
SomeComplicatedPhysicsIntegration( &object->modelviewmatrix);
//modelviewmatrix is a v... |
but I cannot imagine a way that would work without syncing the threads.
No matter what kind of scheme you are using, synchronizing the threads is an absolute essential here. Without synchronization you run the risk that your physics thread will race far ahead of the graphics thread, or vice versa. Your program, typic... |
6,562,368 | 7,018,546 | Retrieve javascript array object with C++ using DISPID_NEWENUM fails on IE9 | following a similar question i answered some time ago, i found out that when trying to enumerate the object, using IDispatch::Invoke(DISPID_NEWENUM,...) fails with DISP_E_EXCEPTION on IE9.
This happens with IDispatch and IDispatchEx, on any javascript array.
needless to say that the code works great on IE6-IE8, and fa... | IEnumVARIANT may work.
Although when I tried it IEnumVARIANT::Next always was returning E_FAIL,
the element was fetched correctly. Didn't have time or need to get to the bottom of this.
It worked for me, but if it didn't I was intended to use IDispatchEx:
when enumerated members of array objects passed by IE they all... |
6,562,431 | 6,562,540 | Ubuntu System Monitor and valgrind to discover memory leaks in C++ applications | I'm writing an application in C++ which uses some external open source libraries. I tried to look at the Ubuntu System Monitor to have information about how my process uses resources, and I noticed that resident memory continues to increase to very large values (over 100MiB). This application should run in an embedded ... | Another tool you can try is the /lib/libmemusage.so library:
$ LD_PRELOAD=/lib/libmemusage.so vim
Memory usage summary: heap total: 4643025, heap peak: 997580, stack peak: 26160
total calls total memory failed calls
malloc| 42346 4528378 0
realloc| 52 7988 ... |
6,562,446 | 6,599,203 | DNS name from NetBIOS name - API function | Is there any API function that can resolve netbios name of a user or group directory object.
I need output in following formats:
NameFullyQualifiedDN - example: CN=John Smith,OU=Users,DC=Engineering,DC=Microsoft,DC=Com
NameDnsDomain - example: engineering.microsoft.com\JSmith
Any other format that gives DNS domain na... | You can use IADsNameTranslate or DsCrackNames to achieve this.
|
6,562,503 | 6,562,542 | how to convert string to variable,vb6/ c#/c++? | How can I convert a string to variable in c# or C++?
example (vb6):
dim a as string
dim b as string
b="halo"
a="b"
msgbox a
this should make a output = halo
is this possible?..,
thanks for the replies
| Edit:
I first misunderstood your answer, but now I see (thx Gserg) that you wish to find a variable based on the name. In C# you have to do this via reflection. See the following code snippet, and make sure that you have referenced System.Reflection.
MyNamespace.MyClass cls = new MyNamespace.MyClass();
FieldInfo fi = c... |
6,562,603 | 6,590,469 | Memcached client library for windows | I wanted to use memcached for my C++ application. To do that I need a client library, similar for example to mysqlclient.
However I'm having a really hard time finding something suitable. Everything seems to be linux only and while some claim to be compatible with windows they require cygwin and other things that I wou... | Did you try this one?
http://code.jellycan.com/memcacheclient/
It claims to be primarily for Windows. Hasn't been updated in a while, but maybe it will work fine for you, and in case it doesn't, probably better to base your own work on it rather than starting from scratch.
|
6,562,686 | 6,565,990 | C++0x issue: Constant time insertion into std::set | According to this page, I can achieve constant time insertion if I use
iterator std::set::insert ( iterator position, const value_type& x );
and the position iterator I provide directly "precedes" the proper (in-order) insertion point.
Now the case I'm concerned with is if I know that the value I'm inserting goes at t... | Is it cheating to run a test instead of reading through library specifications?
For g++-4.4 -O2 for the integers 0 <= i < 5000000 my running times for
standard insertion are
real 0m14.952s
user 0m14.665s
sys 0m0.268s
and my running times for insertion using end() as hint are
real 0m4.373s
user 0m4.148s
sy... |
6,562,771 | 6,562,793 | Memory allocation question in C++ | int main() {
char** k;
k = new char*;
char* k1 = "abc";
char* k2 = "def";
*k = k1;
*(k + 1) = k2;
delete [] (k + 1);
}
Error: segmentation fault
Could someone explain why I get segmentation fault when freeing (k + 1)? I was able to free k with no problems.
ADD: In the answers it has been said that ... | k = new char*;
This allocated storage for only a single char*.
*(k + 1) = k2;
This tries to pretend there are two char*s allocated. This may not be the site of the segfault, but it is the error.
delete [] (k + 1);
Here you're trying to delete[] something you did not new[], another error.
EDIT: Deep down, memory is a... |
6,562,898 | 6,563,218 | wxWidgets: Properly making a user control that contains other controls inside itself | I'm trying to make a user control in wxWidgets to represent a channel in an audio mixer. So, each channel has a standard set of controls inside itself (some sliders, buttons, etc..).
So inside my class I have a sizer in which I add the various child controls I need. So far that works.
But the problems I have are
if I ... | Your controls should be children of your class derived from wxPanel, NOT children of the panel's parent.
faderPan = new mangoFader(parent, 200, false, 55);
should be
faderPan = new mangoFader(this, 200, false, 55);
|
6,562,925 | 6,562,981 | C++ - Issue when using .at() method with string | I have tried Googling and trying everything I can think of, but I can't overcome the problem. So I have come to the masters at StackOverflow!
I am having trouble using the .at() string method:
std::string letters = "QWERTYUIO";
// &(letters.at(0)) now evaluates to QWERTYUIO
// &(letters.at(5)) now evaluates to YUIO
//... | at() returns a reference to the specified character in the string, so when you take its address with &, you get a pointer to that character (of type char *).
The problem is that you are then giving this pointer to something that expects a pointer to an array of chars. This also has the type char * so it type checks jus... |
6,563,005 | 6,563,213 | FLV & F4V open source C++ decoder | I was wondering if anybody knows if there is some type of open source C++ decoder for FLV & F4V video files?
Basically what I need is to input FLV from a file system and to output PNG frame sequence back to the file system. I need the C++ code or the DLLs.
| you can use ffmpeg which is in C or simply run mplayer (check the command line args, it can output the picture sequence)
|
6,563,113 | 6,596,771 | How to compile using CodeBlocks | I download LibCurl from http://curl.haxx.se/download.html (zip type), after I extract, I notice there is Include and Lib folder that has source codes, so I copy those to CodeBlocks project and include it, however when I build it show error
fatal error: curl/curlbuild.h: No such file or directory
The file is inside Inc... | According to the docs/INSTALL file in CURL's source archive, you should build CURL from the command line. If you are using MinGW (bundled with CodeBlocks), you need to make sure the MinGW bin directory is in your PATH variable (set PATH=<path_to_mingw>\bin;%PATH%) and then run mingw32-make mingw32 in CURL's root direct... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.