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 |
|---|---|---|---|---|
3,227,339 | 3,227,365 | What are alternatives to the GetShortPathName function? | I'm looking for a function which can return the 'short' (8.3 notation) path for a given 'long' path. However, the GetShortPathName function (which seemed like a perfect fit) doesn't work for me since it requires thata file with the given long path exists already.
What other options do I have for computing the 8.3 pat... | If the file does not exist, it does not have an 8.3 name. The 8.3 name is created when the file is created. You can of course get the 8.3 pathname for the directory it's in using GetShortPathName on the directory itself, if you need that.
Regardless, this is 2010. It's really backwards to be using 8.3 names for anythin... |
3,227,417 | 3,227,480 | Clarification regarding C++ Exception Handling / Throwing | Consider the following code:
try {
int *i = NULL;
i[100] = 20;
catch (...) {
std::cout << "Exception Caught";
}
When running this code, it crashes (obviously, accessing a NULL pointer).
Although, in Debug mode, Visual Studio states about an Uncaught exception, regarding write access violation.. also understan... | Access violation is not C++ exception and cannot be caught by catch operator. Unhandled exception message in the Output window doesn't mean that this is C++ exception. First-chance and unhandled exception messages are generated both for C++ exceptions and any other exceptions like access violation. Non-C++ exceptions c... |
3,227,434 | 3,227,484 | Problem with passing by reference | Can I overload a function which takes either a reference or variable name?
For example when I try to do this:
void function(double a);
void function(double &a);
I would like the caller of this function to be able to do:
double a = 2.5;
function(a); // should call function(double &a)
function(2.3); // should call func... | I think you're missing the point here. What you really should have is JUST this:
void function(const double &a);
Note the "const". With that, you should always get pass-by-reference. If you have non-const pass by reference, then the compiler will correctly assume that you wish to modify the passed object - which of co... |
3,227,608 | 3,229,532 | How easy is Lua with Qt, compared to QtScript? | I'm just starting C++ development using Qt. However, I'm also interested in using Lua to script my app, given various articles stating its development speed (ease) for writing the workflow/ui/glue of an application. However, out of the box Qt doesn't support it, instead it includes QtScript.
My question is basically sh... | I've encountered the same dilemma. I much prefer Lua to ECMAScript for these sorts of tasks. However, as easy as it is to write Lua bindings, the level of integration provided by QtScript yields a lot of capability out of the box. This includes bindings to built-in QObject-derived classes as well as your own classes th... |
3,228,083 | 3,228,103 | Which STL container for ordered data with key-based access? | Let's say I have a collection of Person objects, each of which looks like this:
class Person
{
string Name;
string UniqueID;
}
Now, the objects must be stored in a container which allows me to order them so that I can given item X easily locate item X+1 and X-1.
However, I also need fast access based on the Uniqu... | boost:bimap is the most obvious choice. bimap is based on boost::multi_index, but bimap has simplified syntax. Personally I will prefer boost::multi_index over boost::bimap because it will allow to easily add more indices to the Person structure in the future.
|
3,228,288 | 3,419,825 | Howto resolve compiler specific runtime initialization functions for a library from the main application | What is the best practice when doing a mixed language library where the library language requires a runtime initialization?
I have a problem where I'd like to create a certain library in Fortran which is to used from C++. I'd want to preserve platform independence and compiler independence if possible. Now, the two com... | There is support for the name mangling and alternative mains (AC_FC_MAIN) in autoconf. I know there were some discussions on this in the cmake group also, so it might be available in the FortranCinterface module. However I could not find any docs on that. I prefer to work with autotools over cmake because these type of... |
3,228,698 | 3,228,721 | Define not evaluating POD? | I was going over the C++ FAQ Lite online. I was browsing inlines again since I haven't found a use for them and wanted to know how the stopped the circular dependency as showed in this answer. I first tried to do the, "Why inlines are better than defines." example with the following code:
#define unsafe(i) \
( (i) ... | Instead of:
#define unsafe(i) \
( (i) >= 0 = (i) : -(i) )
I think you want:
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )
In response to your edit:
After the first call to unsafe(x++), x is 7, even though the ans is 6. This is because you have the statement:
ans = ( (x++) >= 0 ? (x++) : -(x++) )
ans is assi... |
3,228,906 | 3,228,933 | Does std::string::assign takes "ownership" of the string? | I have some gaps in the understanding of string::assign method. Consider the following code:
char* c = new char[38];
strcpy(c, "All your base are belong to us!");
std::string s;
s.assign(c, 38);
Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer; i.e. doesn't allocat... |
Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer;
The STL string method assign will copy the character array into the string. If the already allocated buffer inside the string is insufficient it will reallocate the memory internally. The STL string will not take o... |
3,229,012 | 3,229,964 | Error compiling Visual Studio C++ project - error with cl.exe | I'm running Visual Studio 2005 Pro, and have been getting the following error recently:
Error 1 Error result -1 returned from 'C:\Program Files\Microsoft Visual Studio 8\VC\bin\cl.exe'.
Reading some of the other posts around here, I've learned that cl.exe is native to VS 2008. I do have an install of 2008 Express (bu... | It turns out that the error is not with Visual Studio, but with the test suite that I'm ultimately working with. It replaces cl.exe and link.exe with its own executables, and moves them to different filenames. Fixing some issues with my test suite made it work again.
I didn't realize this until I ran cl.exe from th... |
3,229,084 | 3,229,117 | Is it correct/proper to use DialogBox as the main window? | Is it correct-proper as in windows doesn't say it's bad or not recommended.
For example like this:
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
... | Using a Dialog Box as the main window is actually supported as one of the default configurations by MFC, so yes, that's fine (according to Microsoft).
For what it's worth, virtually every Windows app I've written in years used a dialog box as the main window, but that's because I don't write office-type applications.
|
3,229,333 | 3,229,357 | Finding arguments that go with methods in C++ dll's | Ok, so I can use dumpbin.exe /exports library.dll to find all methods in the dll.
...but how do I find out which arguments to pass into them? Without a header file of course.
| For the usual C-style exports (e.g., Windows API DLLs): You can't. This information is not stored in the DLL and is inevitably lost after compilation (unless you have the headers or debuging symbols).
C++ exports, on the other hand, store their signature as part of the mangled function name and you can view them using ... |
3,229,391 | 3,279,236 | SDL + SDL_ttf: Transparent blended text? | I want to render an anti-aliased string on an SDL_Surface with a given alpha channel.
I figured out it is possible to render:
an anti-aliased string with the Blended variant of the string render method (ie: TTR_RenderText_Blended). But then I can't make it transparent.
An anti-aliased string with the Shaded method. Bu... | Why not use bitmapped fonts? You could build a png image with alpha channel. I think that SDL_ttf works with the same system, it builds an image an internally uses bitmapped fonts.
|
3,229,459 | 3,229,582 | Algorithm to cover maximal number of points with one circle of given radius | Let's imagine we have a plane with some points on it.
We also have a circle of given radius.
I need an algorithm that determines such position of the circle that it covers maximal possible number of points. Of course, there are many such positions, so the algorithm should return one of them.
Precision is not important ... | Edited to better wording, as suggested :
Basic observations :
I assume the radius is one, since it doesn't change anything.
given any two points, there exists at most two unit circles on which they lie.
given a solution circle to your problem, you can move it until it contains two points of your set while keeping the ... |
3,229,660 | 3,229,686 | How to delete object created in another thread in C++ | There is a long-time request and is called from the "main" (UI) thread. It is planned to move it's call into a separate thread. The problem is that some objects are created in this thread on the heap (main thread will have to work with these pointers).
Questions:
Is it allowed to delete 'another-thread' objects in the... |
Yes.
Depending on situation, this is not bad and not good, just do what you need according to your algorithm.
Deleting objects created in another thread may be dangerous only if object destructor works with a thread local storage. This must be mentioned in the class documentation.
|
3,229,807 | 3,229,997 | C++ inheritance/template question | I have two classes, point and pixel:
class point {
public:
point(int x, int y) : x(x), y(y) { };
private:
int x, y;
}
template <class T>
class pixel : public point {
public:
pixel(int x, int y, T val) : point(x, y), val(val) { };
private:
T val;
}
Now here's my problem.... | Question: Do you mean for the private vector to contain both Points and Pixels at the same time, or just one or the other?
Question: If just one or the other, are you meaning to mix Pixels with different template parameters in the same private vector?
Assuming that it is just Point or Pixel in the private vector, and t... |
3,229,883 | 3,229,904 | Static member initialization in a class template | I'd like to do this:
template <typename T>
struct S
{
...
static double something_relevant = 1.5;
};
but I can't since something_relevant is not of integral type. It doesn't depend on T, but existing code depends on it being a static member of S.
Since S is template, I cannot put the definition inside a compil... | Just define it in the header:
template <typename T>
struct S
{
static double something_relevant;
};
template <typename T>
double S<T>::something_relevant = 1.5;
Since it is part of a template, as with all templates the compiler will make sure it's only defined once.
|
3,230,042 | 3,230,108 | Where does the word trait comes from? | I understand that C++ Traits are compile time properties that can be used to take some compile time choices for templates, but where does they come from ?
Can anyone point out some basic background material about the concepts behind traits ?
Where does the word traits come from ?
EDIT: I guess I should refine the ques... | C++ Type traits by John Maddock and Steve Cleary
http://www.boost.org/doc/libs/1_31_0/libs/type_traits/c++_type_traits.htm
Traits: a new and useful template technique by Nathan C. Myers:
http://www.cantrip.org/traits.html
very helpful!
Matthew
|
3,230,319 | 3,322,458 | How to read a user's input from the console into a Unicode string? | A C++ beginner's question. Here is what I have currently:
// From tchar.h
#define _T(x) __T(x)
...
// From tchar.h
#define __T(x) L ## x
...
// In MySampleCode.h
#ifdef _UNICODE
#define tcout wcout
#else
#define tcout cout
#endif
...
// In MySampleCode.cpp
CAtlString strFileName;
if (bIsInterac... | Shouldn't you be using wcin stream if you expect unicode input?
#include <iostream>
#include <string>
#include <locale>
int main()
{
using namespace std;
std::locale::global(locale("en_US.utf8"));
std::wstring s;
std::wcin >> s;
std::wcout << s;
}
|
3,230,354 | 3,230,464 | Finding a Subset of Points by Relative Distances | I'm writing a game in which the player may manipulate a great many objects at one time. I would like the player to be able to select objects according to the distances between them.
Given the locations of all objects, a starting object, and a distance threshold, what is the fastest way to find the subset containing the... | This library seems to do the trick:
"ANN is a library written in the C++ programming language to support both exact and approximate nearest neighbor searching in spaces of various dimensions.
[...]
In the nearest neighbor problem a set P of data points in d-dimensional space is given. These points are preprocessed int... |
3,230,368 | 3,230,443 | boost shared_ptr and 'this' | I have two classes with a parent-child relationship (customer&order directory&file etc)
I have
typedef boost::shared_ptr<Parent> ParentPtr
and in parent class a method to make a child
I need child instances to have pointers to their parent.
class Child
{
....
ParentPtr m_parent;
....
}
I want it to be a share... | I'm fairly sure that enable_shared_from_this solves your problem: http://live.boost.org/doc/libs/1_43_0/libs/smart_ptr/enable_shared_from_this.html
If you derived your class from a specialization of boost::enable_shared_from_this then you can use shared_from_this() in a member function to obtain the shared pointer that... |
3,230,420 | 3,230,454 | How to know if a pointer points to the heap or the stack? | Example:
bool isHeapPtr(void* ptr)
{
//...
}
int iStack = 35;
int *ptrStack = &iStack;
bool isHeapPointer1 = isHeapPtr(ptrStack); // Should be false
bool isHeapPointer2 = isHeapPtr(new int(5)); // Should be true
/* I know... it is a memory leak */
Why, I want to know this:
If I have in a class a member-pointer a... | There is no way of doing this - and if you need to do it, there is something wrong with your design. There is a discussion of why you can't do this in More Effective C++.
|
3,230,681 | 3,231,028 | Read Anonymous Pipes More than Once while Keeping Connection Open (WinAPI) | So I keep bouncing between named and anonymous pipes and here is my issue. I tried named pipes and they just didn't seem to work properly for what I wanted, so I'm back to anonymous pipes. However, the anonymous pipe needs to read input from a pipe (to a program that I did not create) and continuously read it as more i... | It is impossible to guess why it fails if you don't find out why. ReadFile returns FALSE when it fails. You should then call GetLastError() to get a diagnostic.
Never ignore Windows API return values. At the very least assert them.
|
3,230,995 | 3,231,009 | Is this the correct syntax for passing a file pointer by reference? | Is this the correct syntax for passing a file pointer by reference?
Function call: printNew(&fpt);
printNew(FILE **fpt)
{
//change to fpt in here kept after function exits?
}
| No. The correct syntax is
void printNew(FILE *&fpt)
{
//change to fpt in here kept after function exits?
}
Your code will only change the local pointer to a FILE pointer. Only changes to *fpt are seen by the caller in your code. If you change it to the above, things are passed by reference and changes are p... |
3,231,128 | 3,231,692 | Alternative to GLUTesselator? | I was wondering if there was a library or another way to produce multi contour polygons in OpenGL. I did code profiling and the GLUTesselator is killing my loop. Thanks
Bounty
+50 for a library with a GPL-compatible license, and ideally 3D (second best would be 2.5D like GLUtesselator itself.)
| There's always GPC.
EDIT: Some others:
Flipcode mystery triangulator. Slower than GPC in my extremely limited, probably wrong tests.
poly2tri is BSD-licensed.
EDIT2: Earcut.hpp is now a thing.
|
3,231,599 | 3,231,778 | Intercepting a WM_PAINT message and acting upon this | I'm trying to intercept/hook the WM_PAINT message of the desktop in C++. I'm currently drawing with the desktop handle, my only problem is that I'm not in sync so it might flicker.
What I basically would like is a statement where I can check on the WM_PAINT of UINT message.
When this is the case, I want to do something... | I'd check SetWindowHookEx (see: SetWindowsHookEx in C# )
|
3,231,611 | 3,231,779 | Visual C++ Warning C4800, why does it only trigger on return statements? | I have just installed the Windows SDK v7.1 (MSVC 10.0) and running my code through (almost) full warning level (W3, default for qmake's CONFIG += warn_on) and am surprised about warning C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
In the following code, stream is an std::istream and tok... |
What is going on here? I don't even get why the warning is triggered in the first place. I thought the first bit of code already returned a bool anyways.
Streams have an implicit conversion operator that returns a void*. (That's a version of the safe bool idiom. It's done this way because there is less contexts in ... |
3,231,707 | 3,231,808 | A Question About Linking/Loading and A Simulator | I have designed a MIPS I simulator using Verilator which allows me to wrap verilog code into c++. I am attempting to run a c++ program on my processor but I've reached some problems. My goal is to:
write a test program in c++
compile this program using a cross compiler g++ (mips-linux)
take generated ELF file and di... | I have written a full MIPS I simulator that can load ELF binaries. You can get the source code here, maybe you'll get answers to your questions. There are also some demo programs included. The key point is to get the compiler to generate a freestanding executable that does not use any run-time library, not even the gc... |
3,231,739 | 3,231,895 | Problem while building a .dll (Visual C++) | I am trying to build a .dll in order to link it to one of my projects. But the build always fails : I got these messages in the output and I don't know what it means. It seems that something is missing, but I couldn't find what.
I am trying to link a Mesher called Netgen
http://www.hpfem.jku.at/netgen/
1>adfront2.obj ... | seems this NetGen lib's project wants to run a post-build event in which it tries to copy the main output (the nglib.dll) to the directory NETGENDIR (which is supposed to be an environment variable). This fails beccuse the dll isn't found.
Either disable the post build event, or check with the NetGen lib's creator what... |
3,231,924 | 3,232,005 | What should I code to get into the depths of advanced C++? | I'm looking for project suggestions that would force me to "get my hands dirty" with advanced C++ features. I'm talking about projects that would utilize the full power of the language (STL or even boost (didn't use it much yet)).
Why? Because I want to learn, I want to find new challenges. At work, things start to be ... |
What should i code to get into the depths of advanced C++?
Learn more,
learn yet more,
learn even more.
And, no, I'm not joking. Not at all. I started to learn C++ about 15 years ago and I'm still learning new stuff on a regular base.
Have a look at The Definitive C++ Book Guide and List and make your pick.
I'd ... |
3,232,257 | 3,232,470 | calling GetModuleFileNameEx via psapi.dll is not working, but why? | I am using MinGW which does not have full functionality. eg. It has no wchar_t stream support.
I've managed to get around that by writing a mini-set of manipulators (the wcusT() in the code below).. but I find I'm getting stymied again with GetModuleFileNameEx.
I have not been able to natively run GetModuleFileNameEx(... | Your calling GetModuleFileNameEx incorrectly
HWND hWndNPP = FindWindow(_T("Notepad++"),NULL);
DWORD dwBytes = (GetModFnEx)( hWndNPP // this is ment to be a process handle, not a HWND
, NULL, ytcMFqFn, sizeof(ytcMFqFn) );
MSDN doc on GetModuleFileNameEx
you might try getting a process handle using one of the foll... |
3,232,534 | 3,232,577 | Why is my 'count leading zero' program malfunctioning? | Here is code which returns number of leading zeros from Hacker's Delight book:
#include <iostream>
using namespace std;
int nlz(unsigned x) {
int n;
if (x == 0) return(32);
n = 1;
if ((x >> 16) == 0) {n = n +16; x = x <<16;}
if ((x >> 24) == 0) {n = n + 8; x = x << 8;}
if ((x >> 28) == 0) {n = n + 4; x = x << 4;}
if ... | It returns the number of leading bits that is zero in an unsigned integer , and it assumes an integer is 32 bits.
8 is 0000 0000 0000 0000 0000 0000 0000 1000 binary, and it should return 28 for that, as there's 28 leading bits zero before the first 1 bit. If you're running this on something where an integer is not 32 ... |
3,232,545 | 3,232,603 | C++ basic pointer question | I have some shared pointer shared_ptr<T> pointer1(new T(1));.
Now, in some other part of code I have an explicit copy of pointer2 (guess it would be stored in a std::map or some other container). Let's say that copy was done like map.insert(make_pair(key1, pointer1));.
I am using that second copy only to precache some ... | It sounds like this is a task for weak_ptr:
http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/weak_ptr.htm
Try putting them in your table instead of a shared_ptr.
|
3,232,582 | 3,232,905 | Question about using string::swap() with temporaries | The following segment demonstrates my issue: (compilation error on GCC)
stringstream ss;
string s;
ss << "Hello";
// This fails:
// s.swap(ss.str());
// This works:
ss.str().swap(s);
My error:
constSwap.cc:14: error: no matching function for call to 'std::basic_string<char, std::char_traits<char>, std::allocator<cha... | After having used the swap-with-temporary idiom enough times, with lines like
std::vector<int>().swap(v); // clear and minimize capacity
or
std::vector<int>(v).swap(v); // shrink to fit
this does not seem so out of place. It's normal to call swap as a member function of a temporary object. Of course, it's not so idio... |
3,232,614 | 3,232,662 | how does an optimizing c++ compiler reuse stack slots of a function? | How does an optimizing c++ compiler determine when a stack slot of a function(part of stack frame of a function) is no longer needed by that function, so it can reuse its memory? .
By stack slot I mean a part of stack frame of a function, not necessarily a whole stack frame of a function and an example to clarify the m... | The easy part is: When a function exits, all local variables of that function are released. Thus, function exit indicates that the whole stack frame can be freed. That's a no-brainer, though, and you wouldn't have mentioned "optimizing compiler" if that's what you were after.
In theory, a compiler can do flow analysis ... |
3,232,669 | 3,238,215 | Is there an alternative to suppressing warnings for unreachable code in the xtree? | When using the std::map with types that use trivial, non-throwing, copy constructors, a compiler warning/error is thrown (warning level 4, release mode) for unreachable code in xtree. This is because the std::map has a try-catch in it that helps maintain the state of the tree in the case of an exception, but the compil... | Unfortunately it looks like xtree is part of the underlying implementation of map in VC7, and as such there isn't much that can be done to mitigate it. It looks like it's a bug in the standard library.
Is it a possibility to use a newer compiler? I'm fairly sure there are free downloads of more recent versions of the c... |
3,232,705 | 3,232,783 | Pushing back object, then erasing it at its previous location in std::list | Note that the order can go either way (erase first then push back, just that this way doesn't require creating a local reference to the object).
for ( GameObjItr gameObj = m_gameObjects.begin();
gameObj != m_gameObjects.end(); gameObj++ ) {
if ( *gameObj && *gameObj != gameObject ) {
const sf::Float... | When you say:
m_gameObjects.erase( gameObj );
the destructor for the thing contained in the list being erased (if it has one) will be called. It's not clear from your question what the type of this thing is, or if this destructor call is expected.
|
3,232,714 | 3,232,818 | Why is my function returning wrong values? |
Possible Duplicate:
question about leading zeros
As in stackoverflow.com/questions/3232534/question-about-leading-zeros.
Number of trailing zeros, binary search from Hacker's Delight:
#include <iostream>
using namespace std;
int ntz(unsigned x){
int n;
if ( x==0) return 32;
n=1;
if ((x & 0x0000FFFF))==0) {n... | Firstly, your code doesn't compile. The parentheses in lines 9 and 11 are not balanced correctly.
That said, after fixing the errors and compiling, I get the following results:
$ ./a.out
8
3
$ ./a.out
9
0
|
3,232,822 | 3,249,833 | Linking with multiple versions of a library | I have an application that statically links with version X of a library, libfoo, from thirdparty vendor, VENDOR1. It also links with a dynamic (shared) library, libbar, from a different thirdparty vendor, VENDOR2, that statically links version Y of libfoo from VENDOR1.
So libbar.so contains version Y of libfoo.a and my... | Thanks for all the responses. I have a solution that seem to be working.
Here's the problem in detail with an example.
In main.c we have:
#include <stdio.h>
extern int foo();
int bar()
{
printf("bar in main.c called\n");
return 0;
}
int main()
{
printf("result from foo is %d\n", foo());
printf("resul... |
3,232,864 | 3,232,910 | Xerces C++: no error for non-existent file | I'm using the Xerces C++ DOM parser to read some XML files in a Visual C++ project. I have a class with a parse() method that is supposed to read and validate my XML source file. This is what the method looks like:
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/par... | See ErrorHandler documentation.
You must declare and define a class that inherits from ErrorHandler and implements its virtual methods (or you can extend the HandlerBase class).
Then you must call setErrorHandler on your parser instance passing an instance of your error handler, i.e. pDOMParser_->setErrorHandler(your_h... |
3,233,054 | 3,233,114 | error: 'INT32_MAX' was not declared in this scope | I'm getting the error
error: 'INT32_MAX' was not declared in this scope
But I have already included
#include <stdint.h>
I am compiling this on (g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44) with the command
g++ -m64 -O3 blah.cpp
Do I need to do anything else to get this to compile? or is there another C++ way to get ... | #include <cstdint> //or <stdint.h>
#include <limits>
std::numeric_limits<std::int32_t>::max();
Note that <cstdint> is a C++11 header and <stdint.h> is a C header, included for compatibility with C standard library.
Following code works, since C++11.
#include <iostream>
#include <limits>
#include <cstdint>
struct ... |
3,233,078 | 3,233,081 | How does an exception specification affect virtual destructor overriding? | The C++ Standard states the following about virtual functions that have exception specifications:
If a virtual function has an exception-specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall only allow exceptions that are allowed by t... | (1) Does this rule apply to destructors?
Yes, this rule applies to destructors (there is no exception to the rule for destructors), so this example is ill-formed. In order to make it well-formed, the exception specification of ~D() must be compatible with that of ~B(), e.g.,
struct B {
virtual ~B() throw() { }
};
... |
3,233,290 | 3,577,325 | Filtering out namespace errors when parsing partial XML via libxml2 in C++ | I have the need to parse partial XML fragments (which are presented as std::string), such as this one:
<FOO:node>val</FOO:node>
as xmlDoc objects in libxml2, and because these are fragments, I keep getting the namespace error : Namespace prefix FOO on node is not defined errors spit out into STDERR.
What I am looking f... | Building on what @Potatoswatter said... can you create a context for the fragments? E.g. concatenate
<dummyRoot xmlns:FOO="dummy-URI">
in front of your fragment, and
</dummyRoot>
afterward, then pass the concatenated string to xmlParseMemory().
Alternatively, why don't you use xmlParseInNodeContext(), which lets you ... |
3,233,369 | 3,233,384 | About returning references to objects | No, this isn't about the mistake everyone makes of passing locals. I'm just trying to understanding returning a reference to an object you pass in (I'm reading through primer).
So if I have a function like this:
const foo & foo::function2(const foo & val) const
{
using namespace std;
return *this;
}
and then I... | foo object2 = object1.function2(object1);
function2() returns a reference to object1; the foo copy constructor is then invoked to copy object1 into object2, because object2 is declared as a foo object.
If you declared object2 as a const reference instead:
const foo& object2 = object1.function2(object1);
then object... |
3,233,440 | 3,233,530 | How to include a template member in a class? | I am attempting to make a class that has a template object member inside of it. For example
mt_queue_c<int> m_serial_q("string");
However, when I do this it fails to compile. If I move this line outside of the class definition so that it becomes a global object, it compiles fine.
I condensed the code into the small... | This has nothing to with templates in particular - you can't initialize non-static members directly in the class definition (C++03, §9.2/4):
A member-declarator can contain a constant-initializer only if it declares a static member (9.4) of const integral or const enumeration type, see 9.4.2.
If you want to explicitl... |
3,233,445 | 3,233,462 | Is there a way to do this? | Here is my issue. I have a std::vector<POINTFLOAT> Which stores verticies. The issue is that Vertex buffer objects take in a pointer to an array of float. Therein lies my problem. I cannot give it an array of pointfloat. Is there a way that I could instead push pointers to the individual components of each vertex witho... | You can write something like this, ie you have a std::vector which you fill with vertices, and then you call a function (eg an openGL function) which takes a float*. Is that what you want?
void some_function(float* data)
{
}
...
std::vector<float> vec;
vec.push_back(1.2); // x1
vec.push_back(3.4); // y1
vec.push_bac... |
3,233,471 | 3,234,026 | Tool to Map #include's | Is there a tool available which will take a set of source files and map (in graphic fashion) how they are linked via #include?
I would like to see where there are any circular references.
| Red Hat source navigator. Strongly recommended.
|
3,233,513 | 3,233,521 | change value from array | int main()
{
int Count, Sum = 0;
int Group[10];
cout << "-303 to stop\n";
for(Count = 0; Count < 10; Count++) {
cout << "Enter a value: ";
cin >> Group[Count];
if(Group[Count] == -303)
break;
}
int T;
for(T = 0; T < Count; T++)
Sum += Group[T];
f... | Well, just like you can read from Group[T] to print it on the screen, you can assign to Group[T].
So, for example:
for(T = 0; T < Count; T++)
Group[T] *= 2;
|
3,233,693 | 3,234,188 | Call a function twice with Assembly and C++ | I have a code that changes the function that would be called, to my new function, but I don't want to call only my new function, I also want to call the old one.
This is an example, so you can understand what I'm saying:
If I disassemble my .exe, I will look at this part:
L00123456:
mov eax, [L00654321] //doesn... | I had a problem like this a while back. Anyway, _asm call dword ptr [oldfunction] worked for me.
|
3,233,708 | 3,235,091 | share queue between parent and child process in c++ | I know there are many way to handle inter-communication between two processes, but I'm still a bit confused how to deal with it. Is it possible to share queue (from standard library) between two processes in efficient way?
Thanks
| Simple answer: Sharing an std::queue by two processes can be done but it is not trivial to do.
You can use shared memory to hold the queue together with some synchronization mechanism (usually a mutex). Note that not only the std::queue object must be constructed in the shared memory region, but also the contents of th... |
3,233,727 | 3,279,395 | What has to be Glib::init()'ed in order to use Glib::wrap? | So I'm trying to make use of a GtkSourceView in C++ using GtkSourceViewmm, whose documentation and level of support give me the impression that it hasn't been very carefully looked at in a long time. But I'm always an optimist :)
I'm trying to add a SourceView using some code similar to the following:
Glib::RefPtr<gtk... | It turns out, perhaps not surprisingly, that what I needed to init was:
gtksourceview::init();
After this, I ran into another problem with one of the parameter to gtksourceview::SourceLanguageManager, but this was caused by a genuine bug which I subsequently reported and was promptly fixed. So everything's working gre... |
3,233,766 | 3,233,786 | Using both .so and .dll on Windows | I am writing a program in windows in C++ in which users will be able to compile extensions in the form of dynamic-link libraries (windows), or shared object files (linux).
On windows, you use the LoadLibrary function to load a dll. Is it possible to do the same for .so files on windows and vice versa, load .dlls on li... | The short answer is "No"
That is not about loading but about internal format of dynamic library like expected entry points. Each operating system support it's own format. Hence it won't work.
DLL is a PE executable (as are exe on windows)
.so is usually an ELF format (like most modern executables on Linux/Unix).
Howe... |
3,233,987 | 3,235,024 | Deleting a reference | Is this valid? An acceptable practice?
typedef vector<int> intArray;
intArray& createArray()
{
intArray *arr = new intArray(10000, 0);
return(*arr);
}
int main(int argc, char *argv[])
{
intArray& array = createArray();
//..........
delete &array;
return 0;
}
| The behavior of the code will be your intended behavior. Now, the problem is that while you might consider that programming is about writing something for the compiler to process, it is just as much about writing something that other programmers (or you in the future) will understand and be able to maintain. The code y... |
3,234,042 | 3,234,316 | Is there a (Linux) g++ equivalent to the /fp:precise and /fp:fast flags used in Visual Studio? | Background:
Many years ago, I inherited a codebase that was using the Visual Studio (VC++) flag '/fp:fast' to produce faster code in a particular calculation-heavy library. Unfortunately, '/fp:fast' produced results that were slightly different to the same library under a different compiler (Borland C++). As we needed ... | Excess register precision is an issue only on FPU registers, which compilers (with the right enabling switches) tend to avoid anyway. When floating point computations are carried out in SSE registers, the register precision equals the memory one.
In my experience most of the /fp:fast impact (and potential discrepancy)... |
3,234,141 | 3,234,201 | WinAPI Write "Edit" Dialog to Pipe (Error: Stack around variable 'x' was corrupted) | It seems I figured out most of my problems by simply multi-threading my application! However, I am running into a little bit of an error: "Stack around variable 'x' was corrupted." It works properly (after hitting abort on the Debug Error), but obviously I cannot have an error everytime someone runs the application. So... | I don't know where the corruption is happening, so I don't know what exactly the problem is. However, the following line is wrong:
chBuf[BUFSIZE] = '\0';
You declared chBuf with the size BUFSIZE which means that the index BUFSIZE is actually outside of the array. This will result in stack corruption. What you really n... |
3,234,468 | 3,234,623 | How are controls put in the caption bar? | I noticed Firefox 4, Opera and Chrome, and IE 7/8 put buttons and controls in the title/caption bar, how is this done?
Thanks
http://img199.imageshack.us/img199/3307/slayerf.png
alt text http://img199.imageshack.us/img199/3307/slayerf.png
| What they probably do is turn the caption bar off entirely (by excluding the WS_CAPTION window style), add a glass area to the top of the window, and then draw their own controls.
See http://msdn.microsoft.com/en-us/magazine/cc163435.aspx for more on glass.
|
3,234,762 | 3,235,087 | Using bitset in place of using hand written bit manipulation code? | Is there any performance loss/gain using bitset in place where hand written?
How to build the following using a bitset at runtime
make all the bits between 2 and 5 as zero i.e., 11110011.
| The easiest solution to your second question would be to use another bitset.
void makebitszero(bitset<8>& b) {
// Everything but bits 3 and 4 (between 2 and 5).
static const bitset<8> mask = ~bitset<8>(12);
b &= mask;
}
It takes a bit of math to come up with an expression for mask given two bit positions.
[edit]... |
3,234,875 | 3,234,913 | question about Multiply high signed | #include <iostream>
using namespace std;
int mulths(int u,int v)
{
unsigned u0,v0,w0;
int u1,v1,w1,w2,t;
u0 = u & 0xFFFF;
u1 = u >> 16;
v0 = v & 0xFFFF;
v1 = v >> 16;
w0 = u0 * v0;
t = u1 * v0 + (w0 >> 16);
w1 = t & 0xFFFF;
w2 = t >> 16;
w1 = u0 * v1 + w1;
return u1 ... | "Multiply high" returns the high word of the result. E.g. if ints are 32 bits then when you multiply two 32 bit ints you get a 64 bit result. So you can think of this as a 32 bit (signed) high word and a 32 bit (unsigned) low word. E.g. 0x01234567 x 0x456789AB = 0x004EF78252247ACD. High word (signed) = 0x004EF782, low ... |
3,235,073 | 3,235,089 | How do I format c++ comments properly? | Could anyone please suggest a proper format of comments I should use in a C++ project? I think that there is some analog of javadoc format, but I can't find which one. Is there any de-facto standard of that kind? Thanks!
| Doxygen is used rather frequently for C++ projects (Doxygen supports other languages as well). You can use Doxygen-style comments as a starting point (here are some examples). Just be consistent.
|
3,235,228 | 3,235,433 | namespace same name as function | I have this in a header:
double commonFunction( ... )
{ /*...*/ }
namespace F2
{
double impactFactor( ... )
{ /*...*/ }
double func( ... )
{ /*...*/ }
double F2( ... )
{ /*...*/ }
}
namespace FL
{
double impactFactor( ... )
{ /*...*/ }
double func( ... )
{ /*...*/ }
double FL... | Because, using brings every declaration with given name into scope, so if you already have two or more declaration with one name (in this case namespace f1), it will complain.
And it has nothing to do with the name of the namespace and function being the same.
Even this will generate the same error:
namespace foo
{
... |
3,235,424 | 3,265,148 | C++ Sockets Send() Thread-Safety | I am coding sockets server for 1000 clients maxmimum, the server is about my game, i'm using non-blocking sockets and about 10 threads that receive data simultaneously from different sockets (first thread receives from 0-100,second from 101-200 and so on..)
but if thread 1 wants to send data to all 1000 clients and thr... | The usual pattern of dealing with many sockets is to have a dedicated thread polling for I/O events with select(2), poll(2), or better kqueue(2) or epoll(4) (depending on the platform) acting as socket event dispatcher. The sockets are usually handled in non-blocking mode. Then one might have pool of threads reacting t... |
3,235,685 | 3,235,933 | Why doesn't this segfault | I stumbled across something "interesting" and I cant put my finger why the behaviour isn't coherent.
Check this code.
char buf[100];
sprint(buf,"%s",bla);
Simple, right. It's easy to understand what is going on when bla is a NULL pointer.
This should always segfault right!?
In one machine the executable segfaults, on ... | ISO C99: 7.19.6.3 The printf function
Synopsis
#include <stdio.h>
int printf(const char * restrict format, ...);
The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.
7.19.6.1 The fprintf function
7.19.6.1.9
If a conversion specification is invalid, the beh... |
3,235,778 | 3,235,812 | capture a call stack and have it execute in a different thread | I need to write a logging api which does the actual logging on a seperate thread.
i.e. I have an application which wants to log some information. It calls my API and the api captures all the arguments etc and then hands that off to a seperate thread to be logged.
The logger api accepts variadic arguments and therefore ... | You could capture a fixed amount of bytes on the call stack, but you have to copy all that memory even when it's not necessary and put it on a queue of some sort to pass it to the logging thread. Seems like a lot of work to get working, and quite inefficient.
I assume you're using a separate logging thread to make the ... |
3,235,799 | 3,235,859 | How can we use any C library inside our C++ code? | How can we use any C library inside our C++ code? (Can we? Any tuts on that?) (I use VS10 and now talking about libs such as x264 and OpenCV)
| Well you can use any C library from your C++ code. That's one the cool thing with C++ :-)
You just have to include the libraries headers in your C++ code and link with the libraries you use.
Any good library handles its header inclusion from C++. If it is not the case you have to do it yourself with things like :
#ifde... |
3,235,815 | 3,237,465 | CreateCompatibleBitmap failing on Windows mobile 6 | I'm porting an application from Windows Mobile 2003 to Windows Mobile 6, under Visual Studio 2008. The target device has a VGA resolution screen, and I was surprised to find that the following code fails;
CClientDC ClientDC(this);
CRect Rect;
GetClientRect(&Rect);
int nWidth = Rect.Width(),nHeight = Rect.Height();... | I haven't done any Windows CE / Windows Mobile programming, but I have dealt with a similar problem (CreateCompatibleBitmap failing with ERROR_NOT_ENOUGH_MEMORY) in desktop Windows. Apparently, from what I've been able to tell from looking around online, Windows may enforce global limitations on the available memory f... |
3,235,915 | 3,235,966 | Why are IsEqualGUID() and "operator ==" for GUID declared to return int? | Windows SDK features IsEqualGUID() function and operator==() for two GUIDs that return BOOL (equivalent to int):
// Guiddef.h
#ifdef __cplusplus
__inline int IsEqualGUID(REFGUID rguid1, REFGUID rguid2)
{
return !memcmp(&rguid1, &rguid2, sizeof(GUID));
}
#else // ! __cplusplus
#define IsEqualGUID(rguid1, rguid... | Because the Windows API exposes IsEqualGUID() as a function returning a BOOL. They need to keep a stable interface. BOOL and bool are different sizes, and the Windows API is designed to be compatible with a variety of languages and compilers. Remember that there are other languages other than C++ that interact with the... |
3,235,916 | 3,236,027 | A way How to Compile C library into .Net dll? | Can we compile C library as .Net dll (containing and opening access to all C libs functions) by just compiling cpp project containing code like
extern "C" {
#include <library.h>
}
with /clr:pure argument with VS? (VS10)
Or we should do something more trickey?
| I found it is the best to use the old style Managed C++ for this.
CLR:PURE just wont cut it.
Example:
extern "C" int _foo(int bar)
{
return bar;
}
namespace Bar
{
public __gc class Foo
{
public:
Foo() {}
static int foo(int bar)
{
return _foo(bar);
}
};
};
Compile with: /clr:oldSyntax
... |
3,235,927 | 3,236,024 | Reference as key in std::map | Suppose some data structure:
typedef struct {
std::string s;
int i;
} data;
If I use the field data.s as key when adding instances of data in a map of type std::map<std::string&, data>, do the string gets copied? Is it safe to erase an element of the map because the reference will become invalid?
Also do the a... | C++11
Since C++11 reference wrapper is part of standard.
#include <functional>
std::map<std::reference_wrapper<std::string>, data>
Using Boost
You may want to take a look at boost.ref. It provides a wrapper that enables references to be used in STL-containers like this:
std::map<boost::reference_wrapper<std::string>... |
3,236,136 | 3,236,188 | Problems with declarations and initializations | I am trying to rewrite a code I have written earlier.
The code uses cplex concert API;
#include <ilcplex/ilocplex.h>
using namespace std;
ILOSTLBEGIN
int main(){
IloEnv env;
IloModel model(env);
IloVarArray x(env);
IloCplex cplex(model);
return 0;
}
This code (though it doesn... | This code:
solver::solver(){
IloEnv env;
IloModel model(env);
IloVarArray x(env);
IloCplex cplex(model);
}
is not initialising your class members - it is creating local variables in the constructor, which will destroyed when the constructor exits. You want something like:
solver :: solver( IloEnv & env )
... |
3,236,199 | 3,236,586 | VS2010 C++ member template function specialization error | I have the following (minimized) code, which worked in VC2005, but no longer works in 2010.
template <typename TDataType>
class TSpecWrapper
{
public:
typedef typename TDataType::parent_type index_type;
public:
template <bool THasTriangles>
void Spec(index_type& io_index)
{ std::cout << "F... | Workaround
template <bool v> struct Bool2Type { static const bool value = v; };
template <typename TDataType>
class TSpecWrapper
{
public:
typedef typename TDataType::parent_type index_type;
public:
template <bool THasTriangles>
void Spec(index_type& io_index)
{
return SpecHelp(io_... |
3,236,370 | 3,236,398 | Class type from pointer used as template argument | If a pointer to an user defined type is passed as template argument to a template class, is it possible to get the class type of the argument?
template <class T> struct UserType {
typedef T value_type;
...
};
int main () {
typedef std::vector<UserType<double>*> vecType
vecType vec;
vecType::value_... | Use traits:
template <typename> struct ptr_traits {};
template <typename T> struct ptr_traits<T*>
{ typedef T value_type; };
ptr_traits<vecType::value_type>::value_type m;
|
3,236,767 | 3,236,814 | auto_ptr and containers - C++ | I'm currently working on a 2D game engine and I've read about auto_ptr's and how you should never put them in standard containers.
My engine has this structure:
StateManager -- has many --> State's.
States are created and allocated in main, outside of the engine. I want the engine to store a list/vector of all the stat... | Why not use std::vector<State> instead and not worry about storing pointers? It sounds like the list of states is fixed so any iterators will not be invalidated during the lifetime of the program.
Alternatively, I've found the Boost Pointer Container library to be useful for this sort of thing.
|
3,237,201 | 3,237,238 | Pointers to statically allocated objects | I'm trying to understand how pointers to statically allocated objects work and where they can go wrong.
I wrote this code:
int* pinf = NULL;
for (int i = 0; i<1;i++) {
int inf = 4;
pinf = &inf;
}
cout<<"inf"<< (*pinf)<<endl;
I was surprised that it worked becasue I thought that inf would dissapear when the pr... | Your understanding is correct. inf disappears when you leave the scope of the loop, and so accessing *pinf yields undefined behavior. Undefined behavior means the compiler and/or program can do anything, which may be to crash, or in this case may be to simply chug along.
This is because inf is on the stack. Even when i... |
3,237,228 | 3,238,886 | Set Focus to a Cocoa Window in Carbon App | I'm trying to create a Cocoa Window within an otherwise Carbon Application (it's an OpenGL API that uses AGL. Can't change it so don't comment on that).
Here's a code snippit:
WindowRef winref = static_cast<eq::AGLWindow*>(getOSWindow())->getCarbonWindow();
vc = [[SFAttachedViewController alloc] initWithConfig:config... | Did you call NSApplicationLoad() before calling Cocoa methods?
|
3,237,245 | 3,238,123 | dynamic_cast an interface from a shared library which was loaded by lt_dlopen(libtool) doesn't work | This is about plugin features in my program. I need a C++ class(and object) in a plugin could be used by main module through an interface.
The interface inheritance like this:
typedef struct _rwd_plugin_root_t RWD_PLUGIN_ROOT_T;
struct RWD_PLUGIN_API _rwd_plugin_root_t
{
virtual int add_ref() = 0;
virtual int ... | you might try building with -Wl,--export-dynamic linker argument. I recall needing this argument when encountering similar behavior.
|
3,237,247 | 3,237,293 | C++ Rounding to the _nths place | I'm currently learning c++ on a linux machine. I've got the following code for rounding down or up accordingly but only whole numbers. How would I change this code to round to the hundredths place or any other decimal? I wouldn't ask if I didn't try looking everywhere already :( and some answers seem to have a ton of l... | Try
double round( double value )
{
return floor( value*100 + 0.5 )/100;
}
to round to two decimal places.
|
3,237,534 | 7,712,880 | pthread_mutex_lock and unlock | i have two threads, they run pretty fast, i'm using pthread_mutex_lock and pthread_mutex_unlock to access global (externed variables) data
the problem is that my application takes about 15-20% of CPU running on Ubuntu Linux,
the same code but with EnterCriticalSection and LeaveCriticalSection and running on Windows use... | found the fastest way, just use pthread rwlocks!
|
3,237,594 | 3,237,612 | Unused friend class in C++ | Is there a way to detect (for instance with compiler warning) if classes are declared friend but do not access private members, ie. when friendship is useless?
| Compiler warnings are not standardised, so this depends on your specific compiler(s). I would be very surprised if any of them supported this, however. A similar situation would be if you had a public member function which was only called by other public members (meaning it needn't be public), and once again I don't th... |
3,237,642 | 3,238,060 | What to do with "This application has failed to start because myproject.dll was not found." error | I have a project A linked to a project B. B is compiled into a .dll while A is the main program and compiled into a .exe
The compiling of the projects is done without any issues, but when I run the program, I get a pop-up window saying "This application has failed to start because B.dll was not found. Re-installing th... | When Windows loads an EXE, it will check what DLL's are needed, directly or indirectly. In your case, A.EXE will need B.dll. When Windows has determined that list, it will use this procedure to locate the DLLs:
The directory where the executable is stored [1]
The current directory, as set by CreateProcess()
The Window... |
3,237,689 | 3,237,731 | where is the hid.lib file in windows? | I'm doing some HiD programming and I'm trying to locate HiD.lib file to add to my .pro Qt file. However I can't find it. Below is an excerpt of said file:
win32:LIBS+=-lSetupAPI.lib -L"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib" \
-lKernel32.lib -L"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib" ... | You need the Windows Driver Kit for the hid.lib.
|
3,238,246 | 3,238,257 | How to use .Net System.IO; System.Net; System.Net.Sockets; from Visual Studio C++ project? | How to use .Net System.IO; System.Net; System.Net.Sockets; libs from Visual Studio C++ project?
| Those are managed assemblies, meaning you will have to use C++/CLI. Wikipedia has some pretty good information on that: http://en.wikipedia.org/wiki/C%2B%2B/CLI
[edit] Also, of course, there's the MSDN article on C++/CLI: http://msdn.microsoft.com/en-us/library/ms379617(VS.80).aspx
|
3,238,309 | 3,238,655 | Performance of C++ calls to Java code vs C# code | I am exploring a solution at my client where we have to call an API that is available in both C# and Java from our C++ application. We would like this to be a cross platform application (PC & Mac), so Java is preferred, but performance is more important. I've been trying to do some research on the performance of C++ ... | I cannot offer you a definitive answer, but I have done JNI to C library calls (not the reverse), .NET to wrapped Java library calls, and .NET to .NET library calls. I don't have official numbers on any of them, but the .NET to .NET calls, whether managed C++ or C# were both the easiest and fastest. Because they were... |
3,238,329 | 3,238,418 | Class to class conversion using constructor+inheritance in C++ | Here I can do conversion from emp class object to emp class object. But I can't do conversion from employee class object to emp class object - I have added comment where I am getting error - 'setEmpID' is not a member of 'employee'. what should I do to resolve this error? (I am just preparing for C++ exam and this is t... | At the point of call to tmp.setEmpID(10), the definition of class employee is not yet seen by the compiler, since it was just forward declared. So the compiler has no knowledge of the class' methods yet.
In other words this is a cyclical dependency. Luckily it is easy to resolve by moving the implementation of emp(empl... |
3,238,344 | 3,238,414 | c++ what is the advantage of lex and bison to a selfmade tokenizer / parser | I would like to do some parsing and tokenizing in c++ for learning purposes. Now I often times came across bison/yacc and lex when reading about this subject online.
Would there be any mayor benefit of using those over for instance a tokenizer/parser written using STL or boost::regex or maybe even just C?
| I recently undertook writing a simple lexer and parser.
It turned out that the lexer was simpler to code by hand. But the parser was a little more difficult. My Bison-generated parser worked almost right off the bat, and it gave me a lot of helpful messages about where I had forgotten about states. I later wrote the sa... |
3,238,351 | 3,239,358 | Is it possible to transate the wParam parameter into the actual message string? | I am trying to get the actual system messages that are represented by the intergers returned in the wParam property of the message. Is there anyway to do this or a function that can achieve this?
| Is this is a question about WndProc? Which message are you talking about?
LRESULT CALLBACK WndProc(HWND p_hwn,UINT p_msg,WPARAM p_wparam,LPARAM p_lparam)
The WParam is generally used to send flags or info attached to a windows message, it doesn't tell you what the message is.
The message id (p_msg) tells you what ... |
3,238,380 | 3,238,419 | Is increased programming efficiency in Java or C# a myth? | A big advantage of Java or C# in increasing productivity of development is that you're supposed to lose less time with complicated language features, especially those related to memory management. But is it just an impression?
I think that the learning curve for C++ is definitely more steep, but for a proficient C++ pr... |
for a proficient C++ programmer
This is the problem. In my experience, most programmers are NOT proficient. Java allows mindless assembly line workers to be productive in a way that C++ does not.
Proficient developers will be productive no matter what language they write with.
|
3,238,420 | 3,238,802 | Outputting a vector of string objects to a file | I'm trying to output a vector of string objects to a file. However, my code only
outputs the first two elements of each string.
The piece of code below writes:
1
1
to a file. Rather then:
01-Jul-09
01-Jul-10
which is what I need.
ofstream file("dates.out");
vector<string> Test(2);
Test[0] = "01-Jul-09"... | As already observed, the code appears fine, so:
Are you looking at the right dates.out after your program runs? Did you verify the date/time on the file you're looking at to make sure it isn't previous data?
Do you have permission to write to the file? Perhaps your program is failing to overwrite existing data.
Did yo... |
3,238,718 | 3,238,730 | Difference between const variable and const type variable | What is the difference between:
const variable = 10;
and
const int variable = 10;
Does variable, per the standard, get interpreted as an integral type when no type is defined?
| const variable = 10 is not valid C++, while const int variable = 10; is.
The only time (that I can think of) that const variable = 10 would be valid is if you had a type named variable and you had a function with an unnamed parameter of that type, taking a default argument:
typedef int variable;
void foo(const variable... |
3,238,832 | 3,238,882 | How to get the return type of a boost::signal? | I use boost::signal with different function signatures and different combiners.
In a class that looks like the one beyond I want to get the return of a certain signal declaration.
template<typename signal_type> class MyClass
{
signal_type mSignal;
signal_type::result_type getResult() { return mSignal(); }
}
... | You need typename to use dependent types:
typename signal_type::result_type getResult() { return mSignal(); }
Dependent names (i.e. dependent on a template parameter) are assumed to
not name types unless prefixed with typename and to
not name templates unless immediately prefixed with template.
|
3,238,952 | 3,238,993 | Can you force unreferenced code to be linked in from a static library? | Here's the scenario - I have created a custom NSView subclass, and the implementation is in a static library. The class is never referenced from the final executable, only from the Interface Builder XML file. Since it's not referenced, it doesn't get included at link time, and as a result the class can't be found at ru... | You can use the class class method on it, which will mostly be a no-op, but will reference it from your code.
int main(int argc, const char** argv)
{
[MyClass class]; // There you are! MyClass is now referenced from your code.
/* ... rest of your main function ... */
}
|
3,239,090 | 3,311,159 | How you use technique (described) to work with C structures and pointers from .Net? | How you use technique described here to work with C structures from .Net?
Ofcourse I need a code example - on 3 parts: C declaring parts, C++ wrapping around C and C# acsessing.
So what I wonder Is
C structture A has as one of its params structure B which consists of at least 2 types one of which is pointer to some v... | Suppose these are the C structs in a file named structs.h
struct StructB
{
int bMember1;
int bMember2;
int* bMember3;
};
struct StructA
{
struct StructB aMember1;
};
In a new VC++ DLL project, enable Common Language RunTime Support (Old Syntax) and make sure C++ Exceptions are disabled. Build this for... |
3,239,473 | 3,239,548 | C++: Cast to an interface that is not part of the base class | I have a series of classes representing "smart" map elements: MapTextElement, MapIconElement, etc. The classes are extending various Qt graphics item classes, but also provide common functionality, such as an abstract factory method that returns a property panel specialized for each class. I have declared these common ... | With multiple inheritance, dynamic_cast is the only way, and check the return value against NULL.
|
3,239,504 | 3,239,593 | Event filter on QGraphicsItem | Is it possible to have an event filter on a QGraphicsItem? Eventfilter has a param that gives you a QObject, but since QGraphicsItem isn't derived from QObject, then how would it work?
| Edit: Use QGraphicsItem::installSceneEventFilter as suggested in @Frank's answer. Example:
QGraphicsScene scene;
QGraphicsEllipseItem *ellipse = scene.addEllipse(QRectF(-10, -10, 20, 20));
QGraphicsLineItem *line = scene.addLine(QLineF(-10, -10, 20, 20));
line->installSceneEventFilter(ellipse);
// line's events are fil... |
3,239,546 | 3,239,717 | C++ Game State System | Okay: I'm fairly new to C++ and static languages on a whole. Coming from years of ruby (and other dynamic languages) I don't know if this is possible.
I've been making a game state system for... well a game. I want to make the system easy for me to cut and paste into other games without any (or very few) changes.
The t... | For your first problem, yes, you can pass in a type, with some caveats.
I've added a comment under your question, asking for a bit more information. Until we get that, I can't really say how it should be done, but read up on templates.
You can make a function template, which can be passed a type, for example like this:... |
3,239,744 | 3,295,472 | Setting item height of a list view? (using custom draw) | How can I set the row height of a custom drawn list view? Or does it require an owner drawn list view?
| It depends on the mode you are using it in. In some modes, you can use the LVM_SETITEMHEIGHT message. In others some modes, the item height is dictated by the height of an associated ImageList, if any, followed by the height of the assigned Font.
Update: turns out that LVM_SETITEMHEIGHT is part of the MiniGUI library... |
3,239,905 | 3,239,934 | C++ mutex and const correctness | Is there convention regarding whenever method which is essentially read-only, but has mutex/ lock which may need to be modified, is const or not?
if there is not one, what would be disadvantage/bad design if such method is const
Thank you
| You can mark data members with the keyword mutable to allow them to be modified in a constant member function, e.g.:
struct foo
{
mutable mutex foo_mutex;
// ....
void bar() const
{
auto_locker lock(foo_mutex);
// ...
}
};
Try to do this as little as possible because abusing mutabl... |
3,239,968 | 3,240,014 | Detecting precision loss when converting from double to float | I am writing a piece of code in which i have to convert from double to float values. I am using boost::numeric_cast to do this conversion which will alert me of any overflow/underflow. However i am also interested in knowing if that conversion resulted in some precision loss or not.
For example
double source = 19... | You could cast the float back to a double and compare this double to the original - that should give you a fair indication as to whether there was a loss of precision.
|
3,240,005 | 3,240,174 | Design problem relating to manipulating unknown types | I am stuck with a design problem that I hope you guys can help with. I have a few different classes that have various parameters (more than 20 in each case, and they are mostly different, although some are exactly the same in which case they inherit from a base class). I want to control these parameters through the use... | I would suggest first taking a look at boost::any, boost:variant, boost::tuple or boost::fusion::vector as the 'vehicles' for your [data_type].
|
3,240,082 | 3,240,898 | OnRButtonDown on a modal dialog | I have a modal dialog that I would like to implement a right mouse click event on. I have added ON_WM_RBUTTONDOWN() to the class's message map.
BEGIN_MESSAGE_MAP(MyDialog, CDialog)
//{{AFX_MSG_MAP(MyDialog)
ON_WM_RBUTTONDOWN()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
and have overridden the class's afx_msg void O... | No, this should work also in modal dialogs. Two possible scenarios:
you have an invisible control which
captures the click
you have overridden the window procedure and do something unwanted with the message.
|
3,240,241 | 3,242,884 | Recommended practices for re-entrant code in C, C++ | I was going through a re-entrancy guide on recommended practices when writing re-entrant code.
What other references and resources cover this topic?
What lint-like tools can be used to check for these issues?
| The guide is sufficient.
My personal rule of thumbs are only 2 for re-reentering code:
take only pass by value parameters, used only value passed in as parameters in the function.
if I need to use any global parameters or pointer (for performance or storage sake), use a mutex or semaphore to control access to it.
|
3,240,263 | 3,248,175 | Sharing an enum from C#, C++/CLI, and C++ | I have a library that consists of three parts. First is native C++, which provides the actual functionality. Second is a C++/CLI wrapper/adaptor for the C++ library, to simplify the C# to C++ transition. Finally I have a C# library, which invokes the C++ library through the C++/CLI adaptor.
Right now there I have tw... | Just put your #include "Enum.cs" directive inside an outer namespace to resolve the naming collision.
EDIT: A variation suggested by Brent is to use #define to substitute one of the namespaces (or even the enum name itself) declared in the .cs file. This also avoids the naming collision, without making the namespace h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.