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,193,024 | 3,193,881 | Inheritance problem when binding C++ native methods in Chaiscript | I use this code to validate some properties of a set of Qt objects in ChaiScript:
/// initialize the engine
boost::shared_ptr<chaiscript::ChaiScript> chai;
chai.reset(new chaiscript::ChaiScript());
std::cout << "ChaiScript engine created!!!" << std::endl;
///
/// register elements
//
a... | The problem has been solved in the following way:
/// method binding
chai->add(chaiscript::fun<bool (QCheckBox *)>(&QCheckBox::isChecked), "isChecked");
It is necessary to specify that the bound method belongs to the QCheckBox class, in order not to bind the reference to the parent method.
Cheers!!!
|
3,193,201 | 3,193,269 | How does shared_ptr<> safely allow casting to bool? | I was looking into how std::tr1::shared_ptr<> provides the ability to cast to bool. I've got caught out in the past when trying to create a smart pointer that can be casted to bool as the trivial solution, ie
operator bool() {
return m_Ptr!=0;
}
usually ends up being implicitly castable to the pointer type (presuma... | The technique described in the question is the safe bool idiom.
As of C++11, that idiom is no longer necessary. The modern solution to the problem is to use the explicit keyword on the operator:
explicit operator bool() {
return m_Ptr != nullptr;
}
|
3,193,571 | 3,193,676 | C++ alter private member variable from static member function | I noticed while reading through my code that I have a static member function which alters a private member of its class through a pointer to an instance of said class.
It compiles and functions without issue, but I just wanted to know whether or not it was kosher to edit a private variable in this way, from a member bu... | Yes, this is valid.
Although having a non-static member is better in most cases, static members are sometimes used in cases where you need to pass a function-pointer to an external library, like in your case for the pthread library.
If it makes sense to change this private variable in other situations as well, and if y... |
3,193,657 | 3,193,677 | What permissions does a file written with fstream have? | Suppose I create a file for writing like this:
std::ofstream my_file("filename", std::ios_base::out | std::ios_base::trunc);
How are the permissions of this file determined? I've had a program running overnight generating files about once a minute - some are 0644 but others are 0660, and there's nothing in my code tha... | It depends on the umask.
|
3,194,024 | 3,194,071 | How to preserve formatting for C++ streams? | I have the following code (simplified):
ostringstream oss;
oss << "Text ";
oss << hex << uppercase;
oss.width(8);
oss.fill('0');
oss << var1 << " ";
oss << var2 << " ";
oss << dec << nouppercase;
oss.width(1);
oss << var3 << " another text." << endl;
string result = oss.str();
// work with result...
Where var1, ... | Sorry some settings for stream formatting are called volatile (has nothing to do with the keyword), you have to set it each time. See here for explanation.
It will be best to create your own functions.
|
3,194,119 | 3,194,770 | Function pointers working as closures in C++ | Is there a way in C++ to effectively create a closure which will be a function pointer? I am using the Gnu Scientific Library and I have to create a gsl_function. This function needs to effectively "close" a couple of parameters available when I create it. Is there a nice trick to create a closure so that I don't have ... | I found below code at.
http://bytes.com/topic/c/answers/657124-interface-problem
// Use in combination with boost::bind.
template<class F>
static double gslFunctionAdapter( double x, void* p)
{
// Here I do recover the "right" pointer, safer to use static_cast
// than reinterpret_cast.
F* function = st... |
3,194,120 | 3,194,161 | Does "make" know how to search sub-dirs for include files? | This is a question for experienced C/C++ developpers.
I have zero knowledge of compiling C programs with "make", and need to modify an existing application, ie. change its "config" and "makefile" files.
The .h files that the application needs are not located in a single-level directory, but rather, they are spread in m... | This question appears to be about the C compiler driver, rather than make. Assuming you are using GCC, then you need to list each directory you want searched:
gcc -I/foo -I/foo/bar myprog.c
|
3,194,434 | 3,195,119 | C/C++ Dynamic loading of functions with unknown prototype | I'm in the process of writing a kind of runtime system/interpreter, and one of things that I need to be able to do is call c/c++ functions located in external libraries.
On linux I'm using the dlfcn.h functions to open a library, and call a function located within. The problem is that, when using dlsysm() the function ... | I believe the ruby FFI library achieves what you are asking. It can call functions
in external dynamically linked libraries without specifically linking them in.
http://wiki.github.com/ffi/ffi/
You probably can't use it directly in your scripting language but perhapps the ideas are portable.
--
Brad Phelan
http://xtarg... |
3,194,540 | 3,194,616 | Can scanf/sscanf deal with escaped characters? | int main()
{
char* a = " 'Fools\' day' ";
char* b[64];
sscanf(a, " '%[^']s ", b);
printf ("%s", b);
}
--> puts "Fools" in b
Obviously, I want to have "Fools' day" in b. Can I tell sscanf() not to consider escaped apostrophes as the end of the character sequence?
Thanks!
| No. Those functions just read plain old characters. They don't interpret the contents according to any escaping rules because there's nothing to escape from — quotation marks, apostrophes, and backslashes aren't special in the input string.
You'll have to use something else to parse your string. You can write a little ... |
3,194,705 | 3,194,802 | Setting a pointer to null crashes my C++ program | I have a constructor, that receives a character pointer. If it is empty, I need to set its member variable to NULL, however, the program crashes on exit when I try to.
I have verified that it gets to the line where it sets it to NULL and that is the cause of the crash.
I've tried the following:
val = NULL;
val = 0;
... | In the copy constructor you try to delete[] an uninitialized pointer:
LField(const LField &clone) {
//good code here, then...
if (val) //<+ some random address here
delete[] val;//<-undefined behavior
}
just don't do that, skip the whole construct. The copy constructor is invoked on an unitilialized object, t... |
3,194,725 | 3,194,781 | Cross-platform way of constructing an FS path with Qt |
Possible Duplicate:
Qt equivalent of PathAppend?
Short story: does Qt 4 have an analog of Python's os.path.join?
Long story: I need to add a relative path to the application directory, QCoreApplication::applicationDirPath() in the Right Way (TM), so that the code doesn't depend on the file system directory separator... | You can either use "/" directly or use QDir::separator(). But in general use a QDir for this (which translates "/" to the platform specific path separator for you).
|
3,194,730 | 3,263,115 | unordered_map throws bad_alloc in VS10 but not in VS9, is this a bug? | While writing a post about project euler's 14th problem I ran into a difference in behaviour between VC9 and VC10.
The following code runs OK in VC9 but in VC10 std::unordered_map throws a bad_alloc exception.
The strange thing is that if I recover from the exception future allocations will succeed (the size of the con... | It might be incidental, but changing the value of _SECURE_SCL causes the behavoir you describe.
i.e Compiling with:
cl /EHa /MD /D_SECURE_SCL=1 /Ox /c t1.cpp
link /LIBPATH:"c:/Program Files/Microsoft Visual Studio 10.0/VC/lib" /LIBPATH:"C:/Program Files/Microsoft SDKs/Windows/v7.0A/Lib" t1.obj
crashes, but the same co... |
3,195,261 | 3,195,337 | Call a c++ method that returns a string, from c# | Please help,
my c++ function:
extern "C" REGISTRATION_API void calculate(char* msg)
{
//some calculation here
msg = "some text";
}
my c# call:
[DllImport("thecpp.dll")]
static extern void calculate(StringBuilder sMsg);
private void button4_Click(object sender, EventArgs e)
{
StringBuilde... | You are correct that you should use string for LPCTSTR buffers and StringBuilder for LPTSTR buffers.
But you need 2 changes:
1) Set the capacity on your StringBuilder
2) You should be doing strcpy into that buffer, changing what memory address that variable holds won't do anything as you have it now. You need to chang... |
3,195,330 | 3,195,356 | C++: Overwrite an element in a new-created array | If I have an array created like this:
MyType *array = new MyType[10];
And I want to overwrite one of the elements, do I have to delete first the old element like this:
delete &array[5];
array[5] = *(new MyType());
Or is this completely wrong and do I have to work with something like "pointers to pointers" to fix this... | It's an array of values, not of pointers. So you'd just do
array[5] = MyType();
This requires MyType to support the assignment operator.
Incidentally, there's rarely a need for manual array allocation like this in C++. Do away with the new and delete and use std::vector instead:
std::vector<MyType> array(10);
array[5... |
3,195,379 | 3,195,427 | VS 2008 : See the elements referred to pointer | This seems to be a rather stupid question, but I create a pointer to an array of doubles :
double* tab = new double[10];
Then I fill the double array, but when I expand the tab pointer in Debug Mode, I only *tab which gives me the value of first element, which is normal. But how do I see the other elements?
thanks
| If you write in the watch window tab,10 you'll see it as if its a 10 element array.
Be careful though because this can also show you stuff beyond the allocated length of the array.
|
3,195,504 | 3,195,536 | drawing rainbow palettes | I have a 8-bit color palette, therefore I am having 256 colors.
The palette is basically an array of [256 * 3] {r, g, b} values, Now I need to draw a color spectrum out of it. So basically I have to select 256 out of total 256*256*256 values possible which would enable me to draw the rainbow as closely as possible.
Sim... | The HSV solution is still correct, because that pretty much captures your problem. A "rainbow" is by definition a series of colors with constant S and V, but varying H.
|
3,195,788 | 3,195,887 | Algorithm for Audio - Video Encryption | I want to perform encryption - decryption of certain audio - video files.
Can anyone suggest me some suitable algorithms in cocoa, objective- c, c, or c++ to accomplish it?
You can suggest me some link and/ or third party software for it.
Thanks,
Miraaj
| Any stream cipher should work for you. I would suggest AES. Numerous FOSS implementations are available.
Here's a quick link that might help: http://iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html
|
3,195,973 | 3,196,065 | set_union with multiset containers? | What's the return of the algorithm std:set_union when one or both input containers are multisets with duplicated objects? Do dups get lost?
Let's suppose for example:
multiset<int> ms1;
ms1.insert(1);
ms1.insert(1);
ms1.insert(1);
ms1.insert(2);
ms1.insert(3);
multiset<int> ms2;
ms2.insert(1);
ms2.insert(1);
ms2.inser... | From the standard, 25.3.5:
The semantics of the set operations are generalised to multisets in a standard way by defining union() to contain the maximum number of occurrences of every element, intersection() to contain the minimum, and so on.
So in your example, the result will be (1,1,1,2,2,3,4,0,0,0), since you ini... |
3,196,054 | 3,197,807 | Setting a Texture in a shader's constant buffer in D3D10 | Ok I have a shader compiled up under D3D10.
I am obtaining a shader reflection to get details of all the constants/globals in the shader. However I'm a little confused on something ... how do I set a texture to a constant buffer?
I assume I don't just Map the constant buffer and copy the ID3D10Texture pointer into it ... | You don't bind a texture to a constant buffer. You bind textures, via views, to a stage (here GS stage) using method:
void GSSetShaderResources(
[in] UINT StartSlot,
[in] UINT NumViews,
[in] ID3D10ShaderResourceView *ppShaderResourceViews
);
Views and CBs are actually two separate things.
|
3,196,230 | 3,196,298 | file handling routines on Windows | Is it allowed to mix different file handling functions in a one system e.g.
fopen() from cstdio
open() from fstream
CreateFile from Win API ?
I have a large application with a lot of legacy code and it seems that all three methods are used within this code. What are potential risks and side effects ?
| Yes, you can mix all of that together. It all boils down to the CreateFile call in any case.
Of course, you can't pass a file pointer to CloseHandle and expect it to work, nor can you expect a handle opened from CreateFile to work with fclose.
Think of it exactly the same way you think of malloc/free vs new/delete in C... |
3,196,341 | 3,196,362 | Is there a C# equivalent to C++'s std::set_difference? | If so, what is it?
EDIT: In response to comment below:
var tabulatedOutputErrors = from error in outputErrors
group error by error into errorGroup
select new { error = errorGroup.Key, number = errorGroup.Count() };
var tabulatedInputErrors = from error in inputErr... | LINQ has the Enumerable.Except extension method, which seems to be what you're looking for.
Example:
var list1 = new int[] {1, 3, 5, 7, 9};
var list2 = new int[] {1, 1, 5, 5, 5, 9};
var result = list1.Except(list2); // result = {3, 7}
Alternative:
From .NET 3.5 onwards there also exists the HashSet<T> class (and also... |
3,196,395 | 3,196,962 | Is boost::interprocess ready for prime time? | I was working on a thread safe queue backed by memory mapped files which utilized boost interprocess fairly heavily. I submitted it for code review and a developer with more years of experience than I have on this planet said he didn't feel that boost::interprocess was "ready for prime time" and that I should just use... | I attempted to use boost::interprocess for a project and came away with mixed feelings. My main misgiving is the design of boost::offset_ptr and how it handles NULL values -- in short, boost::interprocess can make diagnosing NULL pointers mistakes really painful. The issue is that a shared memory segment is mapped some... |
3,196,464 | 3,196,476 | Pointer to an Element of a Vector | If I have a pointer that is pointing to an element in a vector, say element 2, and then that element gets swapped with element 4 of the same vector. Is the pointer now pointing to element 2, element 4, or neither? Example:
vector a is equal to [1,2,3,4,5]
create pointer that points to the element 2, which is equal to... | You mean, "where is the pointer pointing to?". If that's the case, it'll point to the same location in memory as before which is now occupied by the value 5.
Also, by swapping I assume you meant swapping the values between two locations.
Why?
Simply because your pointer points to a memory location. What's stored there... |
3,196,585 | 3,196,694 | C++: References as constructor arguments, help | I have a base class(Base) whose constructor takes a reference as argument. In my derived class its constructor, I call the superclass-constructor and of course I need to pass a reference as argument. But I have to obtain that argument from a method of which the return type is by value...
I will give a short example:
cl... | Change the Base class to:
class Base
{
public:
Base(const MyType &obj) { /* do something with the obj */}
};
Update: If you want to modify obj you cannot obviously have a const reference. In that case you can either:
1)Pass the parameter by value. That will have the overhead for the copy but avoid ... |
3,196,600 | 3,196,826 | Windows Hashed Password | Is there a way to get the hashed value of Windows password for a specific local user? Which Win32 API would that be? I don't want to know what the actual password is, just the hash value of the password.
I'd like to be able to tell which workstations/servers don't have the same password for a specific user.
Please ad... | I haven't tried this technique recently, so I'm not sure it still works, but at one time it definitely did, and I'd guess it probably still does.
Call NetUserChangePassword for that user's account on each of the target computers, but do it from an account that does not have the right to change that users password (e.g.... |
3,196,968 | 3,197,112 | 3D Graph plotting for C++ | I need to plot my simulation (which I do in a C++ application) for use in a Latex document (so I would prefer some vector output like EPS). My function is of 2 arguments, so I am after a 3D plot, ideally with colouring indicating the function value (similar to what Mathematica does). Could anyone recommend any library?... | Why not use gnuplot? I use it for this sort of thing. If you really need a library, then I'd look at gnuplot++
|
3,196,983 | 3,197,088 | Structure alignment in C++ | struct Vector
{
float x, y, z;
};
func(Vector *vectors) {...}
usage:
load float *coords = load(file);
func(coords);
I have a question about the alignment of structures in C++. I will pass a set of points to the function func(). Is is OK to do it in the way shown above, or is this relying on platform-dependent be... | Structure alignment is implementation-dependent. However, most compilers give you a way of specifying that a structure should be "packed" (that is, arranged in memory with no padding bytes between fields). For example:
struct Vector {
float x;
float y;
float z;
} __attribute__((__packed__));
The above co... |
3,197,025 | 3,197,123 | End of File(EOF) of Standard input stream (stdin) | Does stdin have any EOF? For example, if I start reading from stdin using fread or read, then will the following loop end?
while ((c = read(0, buffer, BUFSIZ)) > 0) {
.
.
.
}
If the answer to this question is no, then is there any way to add EOF to stdin?
| Speaking about EOF in stdin: when you redirect input from file, e.g.:
program <input.txt
the file already has an EOF, so this is not a problem. In console you can simulate EOF flag. In UNIX systems it is Ctrl+D, in Windows Ctrl+Z. When you type this in the console, program will behave like it has just reached end of i... |
3,197,028 | 3,238,529 | How to split audio or write demuxer filter in directshow? | I need to split a PCM audio stream with up to 16 channels into several stereo streams.
As I haven't found anything capable of doing that, I'm trying to write my first directshow filter.
Anything capable of splitting the audio would be very welcomed but I'm assuming that I must do it so there's what I've done:
At first,... | You can take a look at the DMOSample in the Windows Server 2003 R2 Platform SDK. It is also included in older directx sdk's, but not in newer windows sdk's. You can locate it in Samples\Multimedia\DirectShow\DMO\DMOSample. Here is the documentation of this sample.
I have seen someone create a filter based on this whic... |
3,197,292 | 3,197,361 | Avoid global variables/methods name clashes when using C headers in C++ | I recently spent some time chasing an annoying little bug and I'm looking for suggestions for those of you who have either encountered the same problem or know the best way to avoid it.
I have a situation where I am developing in C++ and using strerror and as a result I am using something similar to
extern "C" {
#inclu... | First, it looks like you are using printf style variadic argument list which causes an immediate loss of type safety. You should probably avoid this sort of design in C++.
If you have to do this, then you could consider decorating the function declaration to tell gcc that it is a printf-like function and it will then g... |
3,197,293 | 3,210,761 | DSSCL_EXCLUSIVE not giving exclusive audible output. DirectSound | Very simple question. In the MSDN documentation for the DirectSound API they state that when my application is in focus it will be the only audible program. This is exactly what I want to happen, however when setting this flag and playing sound through my application, I can still hear the background music on my compute... | A long time ago, the Windows developers realized that allowing one application to have total control of the audio system (whereby muting other apps) was a bad idea. And then they subsequently deprecated many of these "exclusive" and foreground/background mode flags. I believe this behavior change goes all the way bac... |
3,197,375 | 3,197,464 | using variables to decide type of class or namespace | Alright, so i had the bright idea of using namespaces and an if statement to change the outcome of variables, in PHP i imagine i could've used concatenation however c++ doesnt seem to have concatenation as far as i can see so far.
so is there a way to get this code to work?
namespace Blue
{
int seven = 7;
int eight =... | I don't think there is a way to do this, and if there were, it's probably a bad idea. You would normally accomplish this behavior in C++ using polymorphism, e.g.:
class Color {
virtual int seven() = 0;
virtual int eight() = 0;
};
class Blue : public Color {
int seven() { return 7; }
int eight() { return 8; }
}... |
3,197,434 | 3,197,454 | C++: Initialize a member pointer to null? | I have a class that looks like:
class Foo
{
public:
Foo();
virtual ~Foo();
private:
Odp* bar;
};
I wish to initialize bar to NULL. Is this the best way to do it?
Foo::Foo() : bar(NULL)
{
}
Also, is it necessary that the destructor is virtual? (If that is true, then must the constructor be virtual as well... |
I wish to initialize bar to NULL. Is this the best way to do it?
It is the correct way. So, yes.
Also, is it necessary that the destructor is virtual?
No. The destructor only needs to be virtual if you will be inheriting from the Foo class and will be using a Foo pointer to delete those derived classes (although as... |
3,197,634 | 3,200,109 | risk related to using winPcap in place of socket | What I have read so far, winPcap allows you to bypass OS and bypass application and transport layer processing for TCP and provides direct access to the link layer.
I am planning to use winpcap to do some user application stuff and not just sniffing. I will be receiving and sending critical information using pcap which... | Sure, there are plenty of risks:
The OS won't know about your privately-managed TCP connections, so it won't know that the port(s) you've chosen is/are in use. This means that it might try to use the same port for another application's connection, leading to chaos.
The OS won't know about your privately-managed TCP c... |
3,197,647 | 3,197,675 | C++: Where to start when my application crashes at random places? | I'm developing a game and when I do a specific action in the game, it crashes.
So I went debugging and I saw my application crashed at simple C++ statements like if, return, ... Each time when I re-run, it crashes randomly at one of 3 lines and it never succeeds.
line 1:
if (dynamic) { ... } // dynamic is a bool member... | Random crashes like this are usually caused by stack corruption, since these are branching instructions and thus are sensitive to the condition of the stack. These are somewhat hard to track down, but you should run valgrind and examine the call stack on each crash to try and identify common functions that might be the... |
3,197,681 | 3,199,716 | Length of boost::iostream::basic_array_sink/source | I'm using to do some serialization stuff "as it can be seen here". That worked fine, but I couldn't figure how to get the size of the written buffer.I've searched on boost documentation and apparently there is no way to do this aside of building a sink/source by myself?
Thanks
| boost::iostreams::basic_array_sink models a SinkDevice only, which gives you write-only semantics and no way of telling how many bytes have been written.
OTOH, its sibling boost::iostreams::basic_array models a SeekableDevice allowing to utilize the seek() member function of your stream:
namespace io = boost::iostream... |
3,197,910 | 3,198,014 | Convert Float to Integer Equivalent | I want to convert a floating point user input into its integer equivalent. I could do this by accepting an input string, say "-1.234" and then I could just explicitly convert each character to it's decimal representation. (big endian by the way). So I would just say for the example I gave,
-1.234 = 1|01111111|001110... | float a = -1.234;
int b = *(int*)&a;
Also, in C++ there's this conversion operator that doesn't do any checks, reinterpret_cast. It's probably better here.
int b = *reinterpret_cast<int*>(&a);
|
3,197,913 | 3,197,919 | Size of #define values | If a value is defined as
#define M_40 40
Is the size the same as a short (2 bytes) or is it as a char (1 byte) or int (4 bytes)?
Is the size dependent on whether you are 32-bit or 64-bit?
| #define has no size as it's not a type but a plain text substitution into your C++ code. #define is a preprocessing directive and it runs before your code even begins to be compiled .
The size in C++ code after substitution is whatever the size is of what C++ expression or code you have there. For example if you suf... |
3,197,928 | 3,198,033 | Are empty initializers preferred for default initializing integral members? | I just read a comment by GMan that
class A
{
public:
A() :
m_ptr() // m_ptr is implicitly initialized to NULL
{ }
};
should be preferred over
class A
{
public:
A() :
m_ptr(NULL) // m_ptr is explicitly initialized to NULL
{ }
};
Notice the lack of NULL in the first example.
Is GMan right? Thi... | I prefer the explicitness. As some of the wrong answers to this question have demonstrated, it's not obvious to everyone that, say, int() and int(0) are equivalent.
I suppose not supplying an explicit value has the advantage that you won't need to revisit the initialization list if you ever change the type.
|
3,197,953 | 3,198,015 | When is the const operator[] called and when is the non-const operator[] called? | I have two very different behaviors for reads and writes. In the event of reads, I want to copy a buffer of a rather hard to extract data structure. On writes, I will just write unbuffered to the structure.
Up to now, I have been using operator[] to do access, so for the sake of polymorphism I'd like to continue doing... | To accomplish what you want, you generally need to have operator[] return a proxy, and overload operator= and operator T (where T is the original type) for that proxy type. Then you can use operator T to handle reads, and operator = to handle writes.
Edit: the basic idea of a proxy is pretty simple: you return an insta... |
3,198,031 | 3,198,143 | Float to String Arduino Compile Error | I'm using this library to convert a float to a string: http://www.arduino.cc/playground/Main/FloatToString?action=sourceblock&ref=1 .
This is the snippet of code, where printing out flt looks like "29.37":
float flt = tempSensor.getTemperature();
char buffer[25];
char str[20];
Serial.print(floatToStri... | In C++ only all last parameters are allowed to have a default value:
BAD rightjustify MUST have a default value:
char * floatToString(char * outstr, float value, int places,
int minwidth=0, bool rightjustify) {
OK: no default values, last or two last parameters have default values
char * floatToString(char * outst... |
3,198,107 | 3,198,251 | C++: Difficulty with removing an item from a vector | I'm trying to remove an element from a vector.
vector<Foo> vecFoo;
Foo f1;
Foo f2;
Foo f3;
vecFoo.push_back(f1);
vecFoo.push_back(f2);
vecFoo.push_back(f3);
Foo* pF1 = &f1;
vecFoo.erase(std::remove(vecFoo.begin(), vecFoo.end(), *pF1), vecFoo.end());
That last line produces a huge amount of C2784 errors. What am I ... | Are you missing the comparison operator?
class Foo
{
public:
bool operator==(Foo const& rhs) const { return true;}
... Other stuff
};
|
3,198,249 | 3,198,376 | Sharing static members between template instantiations? (impossible?) | I am doing something that is probably silly, but it would be nice if it worked.
I am attempting to specialize types in a way that I need my own lookup structure that is essentially global (but ideally encapsulated as a class variable), but I want the objects to be type safe, so they are parameterized.
Consequently, I h... | You could add a non-templated base class and move lookupTable into that class:
class Base
{
protected:
static map<string, internal_t> lookupTable
};
template<class T, int N>
class SpecialArray : Base
{
//...
};
|
3,198,302 | 3,198,323 | C++ MySQL and multithreading - 1 DB connection per user? | Is in multithreaded application suitable to have 1 connection per 1 connected client? To me it seems ineffective but if there is not connection pooling, how it could be done when one wants to let each connection communicate with DB?
Thanks
| If you decide to share a connection amongst threads, you need to be sure that one thread completely finishes with the connection before another uses it (use a mutex, semaphore, or critical section to protect the connections). Alternately, you could write your own connection pool. This is not as hard as it sounds ... m... |
3,198,521 | 3,198,583 | What to do with template typenames for optional arguments? | First of all, the code:
template<typename Func, typename Func2>
void ForEachField(Func normalHandler, Func2 arrayHandler = NULL, bool skipUnknowns = true)
{
for(int i = 0; i < mFields.size(); ++i)
{
Field *f = mFields[i];
if(skipUnknowns && f->IsUnknown())
continue;
if(f->G... | You could add an overload for ForEachField:
template<typename Func>
void ForEachField (Func normalHandler)
{
ForEachField<Func, void *>(normalHandler, NULL, true);
}
|
3,198,569 | 3,198,613 | Reverse doubly-link list in C++ | I've been trying to figure out how to reverse the order of a doubly-linked list, but for some reason, in my function void reverse() runs while loop once and then crashes for some reason. To answer some questions ahead, I'm self-teaching myself with my brothers help. This isn't all of the code, but I have a display() ... | Try this:
node *ptr = start_ptr;
while (ptr != NULL) {
node *tmp = ptr->nxt;
ptr->nxt = ptr->prv;
ptr->prv = tmp;
if (tmp == NULL) {
end_ptr = start_ptr;
start_ptr = ptr;
}
ptr = tmp;
}
|
3,198,750 | 3,198,775 | new types may not be defined in a return type - C++ | I am confused I think on C++ class structure.
I have a .h called FxMathFunctions.h and a .cpp called FxMathFunctions.cpp
the .h starts like:
class FxMathFunctions
{
public:
FxMathFunctions();
~FxMathFunctions();
and in the .cpp
I have:
#include "FxBasicTypes.h"
#include "FxMathFunctions.h"
FxMat... | What does your .h file end with? I'm guessing that the end of your class defnition does not have a ";". The class is being interpreted as the return type of the first function in your cpp file.
|
3,198,904 | 3,202,333 | D3D10 HLSL: How do I bind a texture to a global Texture2D via reflection? | Ok so assuming I have, somewhere in my shader, a statement as follows (Note I am enabling legacy support to share shaders between DX9 and DX10):
Texture2D DiffuseMap;
I can compile up the shader with no problems but I'm at a slight loss as to how I bind a ShaderResourceView to "DiffuseMap". When I "Reflect" the sha... | Hmm let me rephrase that. On the C++ side you have a bunch of loaded textures and associated SRVs. Now you want to set a shader (that comes from DX9) and without looking at how the shader is written, bind SRVs (diffuse to diffuse slot, specular, normal maps—you name it). Right?
Then I think as you said that you best b... |
3,198,965 | 3,198,992 | How to call execute command line in C++ | For example, I have a script ./helloworld.sh
I would like to call it in C++, how do I do that? Which library can be used?
| try
system("./helloworld.sh");
|
3,199,067 | 3,264,887 | C++ catching dangling reference | Suppose the following piece of code
struct S {
S(int & value): value_(value) {}
int & value_;
};
S function() {
int value = 0;
return S(value); // implicitly returning reference to local value
}
compiler does not produce warning (-Wall), this error can be hard to catch.
What tools are out there to h... | There are runtime based solutions which instrument the code to check invalid pointer accesses. I've only used mudflap so far (which is integrated in GCC since version 4.0). mudflap tries to track each pointer (and reference) in the code and checks each access if the pointer/reference actually points to an alive object ... |
3,199,139 | 3,199,155 | Nested NameSpaces in C++ | I am confused what to do when having nested namespaces and declarations of objects.
I am porting some code that links against a static library that has a few namespaces.
Example of what I am talking about:
namespace ABC {
namespace XYZ {
//STUFF
}
}
In code what do I do to declare an object that is i... | It depends on the namespace you already are:
If you're in no namespace or another, unrelated namespace, then you have to specify to whole path ABC::XYZ::ClassA.
If you're in ABC you can skip the ABC and just write XYZ::ClassA.
Also, worth mentioning that if you want to refer to a function which is not in a namespace (o... |
3,199,429 | 3,199,441 | Accessing an enum in a namespace | In a header I have a setup like this
namespace NS {
typedef enum { GOOD, BAD, UGLY }enum_thing;
class Thing {
void thing(enum_thing elem);
}
}
and of course another cpp file that goes along with that header. Then I have a thread cpp file that contains main(). In this cpp file I use that enum to pas... | Can you avoid using a typedef? Just do:
enum Foobar {good, bad, hello};
|
3,199,494 | 3,199,508 | Create a function pointer which takes a function pointer as an argument | How to create a function pointer which takes a function pointer as an argument (c++)???
i have this code
#include <iostream>
using namespace std;
int kvadrat (int a)
{
return a*a;
}
int kub (int a)
{
return a*a*a;
}
void centralna (int a, int (*pokfunk) (int))
{
int rezultat=(*pokfunk) (a);
cout<<r... | You need to use the function pointer type as the type of the parameter:
void (*cent) (int, int (*)(int)) = ¢ralna
|
3,199,735 | 3,199,763 | C++ timeout on getline | I need all of my threads to check periodically that they should still be running, so that they can self-terminate when the program ends. For all but one of them, this is just a matter of checking a state variable, but the last one is a user-interaction thread, and its loop will wait indefinitely on user input, only che... | There is no (standard) way to set a timeout on std::getline. In particular, the C++ standard library does not know the existence of threads
To answer your second question, the standards-compliant version of std::getline is the one in the namespace.
|
3,199,747 | 3,199,916 | How can I set up a CBT hook on a Win32 console window? | I've been trying to set up a CBT hook for my C++ Console application with the following code:
...includes...
typedef struct _HOOKDATA
{
int type;
HOOKPROC hookproc;
HHOOK hhook;
}_HOOKDATA;
_HOOKDATA hookdata;
//CBT
LRESULT CALLBACK CBTProc(int code, WPARAM wParam, LPARAM lParam)
{
//do not ... | The problem is that SetWindowHookEx is based upon the Win32 message handling model. Console windows are children of the Kernel itself and do not create their own message pumps or windows.
AFAIK doing what you want directly is not possible.
|
3,199,761 | 3,199,817 | Define BIT0, BIT1, BIT2, etc Without #define | Is it possible in C++ to define BIT0, BIT1, BIT2 in another way in C++ without using #define?
#define BIT0 0x00000001
#define BIT1 0x00000002
#define BIT2 0x00000004
I then take the same thing and make states out of those bits:
#define MOTOR_UP BIT0
#define MOTOR_DOWN BIT1
Note: I am using 32 bits only, not 64 bits... | How about:
enum Bits
{
BIT0 = 0x00000001,
BIT1 = 0x00000004,
BIT2 = 0x00000008,
MOTOR_UP = BIT0,
MOTOR_DOWN = BIT1
};
|
3,199,839 | 3,199,856 | Fastest way of doing transformations (Move, Rotate, Scale) | I was looking at this vector drawing application called Creative Docs .Net . I noticed that I can have hundreds of shapes and moving, rotating and scaling do not lag at all. Given that all verticies must be modified, how do applications generally do these transformations as quickly as possible?
Thanks
| One typical way to do it is to apply a 3x3 (or 3x2, or 2x3) affine transformation matrix to the coordinates, which can describe things like position, rotation, scale and shear.
If you use OpenGL or Direct3D you can use the graphics hardware to do the actual transformations for you.
If you do it in software, rasteration... |
3,199,892 | 3,199,949 | Determining wether a class has a certain member? |
Possible Duplicate:
Possible for C++ template to check for a function’s existence?
I am trying to determine wether a type has a certain member. This is what i tried:
template <typename T,typename U=void>
class HasX
{
public:
static const bool Result=false;
};
template <typename T>
class HasX<T,typename enable_i... | There is indeed:
typedef char (&no_tag)[1];
typedef char (&yes_tag)[2];
template < typename T, void (T::*)() > struct ptmf_helper {};
template< typename T > no_tag has_member_foo_helper(...);
template< typename T >
yes_tag has_member_foo_helper(ptmf_helper<T, &T::foo>* p);
template< typename T >
struct has_member_fo... |
3,199,995 | 3,200,128 | Synchronizing access to a return value | Consider the following C++ member function:
size_t size() const
{
boost::lock_guard<boost::mutex> lock(m_mutex);
return m_size;
}
The intent here is not to synchronize access to the private member variable m_size, but just to make sure that the caller receives a valid value for m_size. The goal is to preve... | Both of your example constructs will do what you're looking for. The following information from the standard supports the behavior you're looking for (even in your 1st example):
12.4/10 Destructors:
Destructors are invoked implicitly ... for a constructed object with automatic storage duration (3.7.2) when the block i... |
3,200,083 | 3,200,140 | Set the backcolor of a WinAPI toolbar with Visual Styles? | Is there a way to set the background color. I thought of making a dummy window and then using TBSTATE_TRANSPARENT, but I thought there might be a cleaner solution?
Thanks
None of these solutions work for a toolbar using visual styles
| Check out TB_SETCOLORSCHEME.
|
3,200,117 | 3,200,136 | What are "cerr" and "stderr"? | What is the difference between them and how are they used?
Can anyone point me to examples?
Specifically, how do you "write" to the stream in both cases and how do you recover and output (i.e. to the screen) the text that had been written to it?
Also, the "screen" output is itself a stream right? Maybe I don't understa... | cerr is the C++ stream and stderr is the C file handle, both representing the standard error output.
You write to them the same way you write to other streams and file handles:
cerr << "Urk!\n";
fprintf (stderr, "Urk!\n");
I'm not sure what you mean by "recover" in this context, the output goes to standard error and t... |
3,200,235 | 3,200,382 | Makefile updated library dependency | I have a large makefile which builds several libraries, installs them, and then keeps on building objects which link against those installed libraries. My trouble is that I want to use "-lfoo -lbar" as g++ flags to link against the two installed libraries, but the dependencies get messed up. If I change a header "42.... | As far as I know, make in general isn't very good at automatically detecting dependencies like this. (It's not really make's job; make is a higher-level tool that's not aware of the specifics of the commands that it's spawning or what those commands do.)
Two options come to mind.
First, you could run ldd on $(myObject... |
3,200,436 | 3,201,142 | casting from binary to multi-dimensional array on heap | i'm currently using binary files for quick access to custom objects stored in multidimensional arrays which are saved to file as object arrays. so far, reading from file hasn't been too much of a problem since i've been reading the array into an identical object array on the stack. it looks something like this:
Foo foo... | To my opinion here it makes not much sense to use C++ mechanisms to allocate / deallocate, since you overwrite the data completely by your reads. So don't do new / delete stuff. Your cast (char*) is in fact a reinterpret_cast< char* >. Why not just use a malloc with the correct size?
typedef Foo largeFoo[500][1000];
la... |
3,200,441 | 3,200,529 | Data structure that can hold multiple types of data | Like the title says, I'm looking for some kind of data structure which will allow me to store any type of class into it that I need at the time. For example:
Foo *foo = new Foo();
Bar *bar = new Bar();
someContainer.push_back( foo );
someContainer.push_back( bar );
someContainer.access( 0 )->doFooStuff();
someContainer... | Have a common base class for all of your multiple types. Have the data structure hold onto pointers of your base class's type.
|
3,200,597 | 3,200,669 | (kind of) rotating and slicing elements of a container in C++ | I have a std::vector that holds a Point struct (x,y,z and some other non-pointer types).
These points are control points for drawing a bspline curve. I'm not having trouble drawing the curve, but complications arise when I have to close the curve, which involves adding control points (alredy existing inside the contain... | What, exactly, is wrong with using std::rotate()? For example,
std::vector<int> v(5);
std::rotate(v.begin(), v.begin() + 1, v.end());
std::vector<int> firstFour(v.begin(), v.begin() + 4);
firstFour then contains the first four elements from the rotated vector. If you use this in a loop and run it v.size() times, yo... |
3,200,705 | 3,200,724 | Libraries for standard stuff (ie: cout, etc) *NEWBIE QUESTIONS* :) | I was wondering about the standard C libraries that contain all the functions/definitions like abs(), cout streams, printf, etc.
I'm familiar with the header files (stdio.h, cmath.h, time.h, etc etc) but there doesn't seem to be any corresponding .lib or .dll anywhere (ie. stdio.lib, time.dll, etc).
Where is the actual... | It depends on the implementation. On Windows, the standard library functionality is in the C and C++ runtime libraries. The C runtime library is always linked in automatically; the C++ runtime library is linked in automatically if you include one of the standard library headers.
|
3,201,273 | 3,206,140 | What is the correct way of Multiple inheritance in Qt/C++? | In my Qt application, I have a base class as follow. I am using QObject because I want to use Signal-Slot mechanism in all derived classes.
class IRzPlugin : public QObject {
public:
virtual void registerMenu(QWidget*);
virtual void execute();
}
Then I have another class as follow. I need to extend from QWidget b... | In the current incarnation, it isn't possible to use QObject in multiple inheritance paths for a derived class (like your IRzLayeringPlugin class). The only solution I've ever seen was to create an interface class without any QObject inheritence, but with functions that directly correspond to the QObject functions you... |
3,201,342 | 3,201,355 | Meaning of #undef in C++ | I know what this means
#define M(B) (1U << ((sizeof(x) * CHAR_BIT) - B)) // CHAR_BIT=bits/byte
but I don't understand well this one:
#undef M
after this what happens? M is cleared or deleted or?
| After the #undef, it's as if the #define M... line never existed.
int a = M(123); // error, M is undefined
#define M(B) (1U << ((sizeof(x) * CHAR_BIT) - B))
int b = M(123); // no error, M is defined
#undef M
int c = M(123); // error, M is undefined
|
3,201,522 | 3,201,553 | C++ writing/reading hex values correctly (CryptoPP) | I am trying to run a program, that encrypts and decrypts using AES.
(from http://www.codeproject.com/KB/security/AESProductKey.aspx )
// From aestest1.cpp
// Runtime Includes
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include "stdafx.h"
// Crypto++ Includes
#include... | You need to disable text processing, which messes up newline characters.
Try
ofstream write ("text.txt", ios::out | ios__binary);
and
ifstream read ("text.txt", ios::in | ios::binary);
|
3,201,549 | 3,201,574 | How to pass parameters to a constructor? | I've got a class A, which consists of objects B and C. How to write a constructor of A that gets B and C objects? Should I pass them by value, by (const) reference, or a pointer? Where should I deallocate them?
I thought about pointers, because then I could write:
A a(new B(1,2,3,4,5), new C('x','y','z'))
But I don't ... | Usually you pass by const reference:
A a(B(1,2,3,4,5), C('x','y','z'))
No need for pointers here.
Usually you store values unless copying is too inefficient.
The class definition then reads:
class A {
private:
B b;
C c;
public:
A(const B& b, const C& c): b(b), c(c) { }
};
|
3,201,840 | 3,202,743 | c++ compile error in codechef.com | I am trying to submit the solution of Adding Least Common Multiples(July contest) in codechef.com.
But
After submission I have got an error
/sources/tested.cpp:1: error: expected unqualified-id before numeric constant
what is it mean?
I did not get any error when I compiled in eclipse(helios) using mingw32-g++
| Can you copy paste your line of code which is causing this error?
This can happen for various reasons.
There can be name collisions wherein you decalare some variable which conflicts with some preprocessor constant.
Passing references to temporary objects as parameters wherein the function expects a reference to some... |
3,202,136 | 3,202,161 | Using G++ to compile multiple .cpp and .h files | I've just inherited some C++ code that was written poorly with one cpp file which contained the main and a bunch of other functions. There are also .h files that contain classes and their function definitions.
Until now the program was compiled using the command g++ main.cpp. Now that I've separated the classes to .h a... | list all the other cpp files after main.cpp.
ie
g++ main.cpp other.cpp etc.cpp
and so on.
Or you can compile them all individually. You then link all the resulting ".o" files together.
|
3,202,168 | 3,202,564 | Using static class data in std::max and min | I have a static class data member declared as:
static const float MINIMUM_ZOOM_FACTOR = 4.0;
I'm using this constant in a class member function like this:
zoomFactor_ = max(zoomFactor_, MINIMUM_ZOOM_FACTOR);
At this point, the compiler complains that MINIMUM_ZOOM_FACTOR is an undefined reference. However if I use it ... | Only integer constants can be defined inside the class like that. Floating point (or class type) constants must be declared in the class, and then defined and initialised once outside. In practice, that means you must define it in a source file.
// header file
class thingy
{
static const float MAXIMUM_ZOOM_FACTOR;
... |
3,202,234 | 3,202,280 | overloaded functions are hidden in derived class | In a derived class If I redefine/overload a function name from a Base class,
then those overloaded functions are not accessable/visible to derived class.
Why is this??
If we don't overload the oveloaded function from the base class in derived class
then all the overloaded versions of that function are available to d... | TTBOMK this doesn't have a real technical reason, it's just that Stroustrup, when creating the language, considered this to be the better default. (In this it's similar to the rule that rvalues do not implicitly bind to non-const references.)
You can easily work around it be explicitly bringing base class versions int... |
3,202,320 | 3,202,356 | How to make template type inference work in this case? | Once again, I wish C++ had stronger typedefs:
#include <vector>
template<typename T>
struct A {
typedef std::vector<T> List;
};
template<typename T>
void processList(typename A<T>::List list) {
// ...
}
int main() {
A<int>::List list;
processList<int>(list); // This works.
processList(list); ... |
is there any way to make template type inference work for me?
No, this is what's called a non-deducible context.
However, why do you need this anyway? The idiomatic way to pass sequences around is by iterator:
template<typename It>
void processList(It begin, It end) {
typedef typename std::iterator_traits<It>::... |
3,202,520 | 3,203,429 | C++ - Memory leak testing with _CrtDumpMemoryLeaks() - Does not output line numbers | I'm working on a game with SDL in Visual Studio 2010. I came across the _CrtDumpMemoryLeaks() macro and thought I'd give it a go. Invoking _CrtDumpMemoryLeaks() does print memory leaks to the output window, but it does not show where it happens.
I've read the MSDN article at Memory Leak Detection Enabling , and it expl... | When you define _DEBUG and include <crtdbg.h> you get an overloaded operator new which takes additional parameters which you can use to specify the file and line numbers in placement new expressions.
E.g.
int* p = new (_NORMAL_BLOCK, __FILE__, __LINE__) int(5);
You can wrap this in a conditionally defined macro, e.g.
... |
3,202,761 | 3,202,839 | C++ Precision: String to Double | I am having a problem with precision of a double after performing some operations on a converted string to double.
#include <iostream>
#include <sstream>
#include <math.h>
using namespace std;
// conversion function
void convert(const char * a, const int i, double &out)
{
double val;
istringstream in(a);
... | This is almost an exact duplicate of so many questions here - basically there is no exact representation of 34.38 in binary floating point, so your 34 + 19/50 is represented as a 34 + k/n where n is a power of two, and there is no exact power of two which has 50 as a factor, so there is no exact value of k possible.
I... |
3,202,822 | 3,202,892 | When to catch boost::bad_lexical_cast | From the documentation on the boost site for lexical cast it states that when converting from a numeric type to a string type the conversion can throw a bad_lexical_cast. Clearly in this case we should always handle this exception should it be thrown.
My question is, what about the other way around, going from a numeri... | As far as I know, there is no scenario in which an inbuilt numeric type can fail to be expressed in a string.
|
3,203,162 | 3,203,180 | What does sizeof do? | What is the main function of sizeof (I am new to C++). For instance
int k=7;
char t='Z';
What do sizeof (k) or sizeof (int) and sizeof (char) mean?
| sizeof(x) returns the amount of memory (in bytes) that the variable or type x occupies. It has nothing to do with the value of the variable.
For example, if you have an array of some arbitrary type T then the distance between elements of that array is exactly sizeof(T).
int a[10];
assert(&(a[0]) + sizeof(int) == &(a[1]... |
3,203,226 | 3,203,522 | How to use RTF export feature of KDE? | In stackoverflow.com I have found a question where a user was suggesting to use this libraries of KDE in order to export-inport RTF files. But, when I downloaded I saw that there are lot of files that are included in the .cc and .h files that are missing. So please give a hint how to download all necessary files and is... | First off, as you mention, that code is part of the KDE project. Its code base is very large, so in the worst case you'd have to provide most of kdebase-dev. The following link contains a tutorial for building KWord from SVN, which will pull in all the dependencies you need (then you can start deleting them as you find... |
3,203,305 | 3,203,356 | Write a function that accepts a lambda expression as argument | I have a method like this
template<typename T, typename U>
map<T,U> mapMapValues(map<T,U> old, T (f)(T,U))
{
map<T,U> new;
for(auto it = old.begin(); it != old.end(); ++it)
{
new[it->first] = f(it->first,it->second);
}
return new;
}
and the idea is that you'd call it like this
BOOST_AUTO_T... | Your function is expecting a function pointer, not a lambda.
In C++, there are, in general, 3 types of "callable objects".
Function pointers.
Function objects.
Lambda functions.
If you want to be able to use all of these in your function interface, then you could use std::function:
template<typename T, typename U>
m... |
3,203,365 | 3,203,426 | Problem with linking against a static library which has inline functions | i have a static library which (among other things) implements a tiny function that only returns some string from a table of const strings. This function is not called anywhere inside the library, but still it's declared as inline. For clarity, it looks like this:
namespace flow
{
inline const char* GetName( BYTE me... |
1) Why does this error appear? How can i fix it without modifying the static library source code (without removing the inline keyword)?
There's no point in declaring functions as inline. You have to define them in the header anyway:
namespace flow
{
inline const char* GetName( BYTE methodType )
{
if ... |
3,203,452 | 3,203,502 | How to read entire stream into a std::string? | I'm trying to read an entire stream (multiple lines) into a string.
I'm using this code, and it works, but it's offending my sense of style... Surely there's an easier way? Maybe using stringstreams?
void Obj::loadFromStream(std::istream & stream)
{
std::string s;
std::streampos p = stream.tellg(); // remember ... | How about
std::istreambuf_iterator<char> eos;
std::string s(std::istreambuf_iterator<char>(stream), eos);
(could be a one-liner if not for MVP)
post-2011 edit, this approach is now spelled
std::string s(std::istreambuf_iterator<char>(stream), {});
|
3,203,885 | 3,203,956 | Uninitialized Automatic variable forcing value to random value | This may look like a trivial problem. Sorry in that case, I am not able to find the actual way. I understand that automatic variable are un-initilaized. So a code snippet provided below is likely to dump in block-2
char *p;
if(NULL == p)
{
//do something block-1 statement
}
else
{
//do something el... | What you see here is an artifact of how memory is usually allotted to processes on Unix.
Since the stack segment is not stored in the disk-file image of the executable the OS has to allocate new pages to the stack at program start. These come as zero-filled initially, same as the .bss. This initial zero-filling of the ... |
3,204,001 | 3,205,638 | C++ / openGL: Rotating a QUAD toward a point using quaternions | When I have a QUAD at a certain position, how can I rotate it in such a way that its normal points toward a given point? Imagine the colored blocks are just rectangular quads, then this image shows a bit what I mean. The quads are all oriented in such a way they point toward the center of the sphere.
alt text http://em... | Rotation axis = normalize(crossproduct(currentNormal, desiredNormal))
Rotation angle = acos(dotproduct(normalize(currentNormal), normalize(desiredNormal)).
You can build either rotation matrix or quaternion from axis and angle. Exact formula can be found in any resource about quaternions.
You may need to flip angle or ... |
3,204,313 | 3,204,353 | How do I make my BigInt and BigFraction classes interact with fundamental data types in C++ | I created my own big integer class, and big fraction class (which stores the numerator and denominator as 2 BigInt member variables). I overloaded the +,-,*,/ operators and the classes work fine. Now I want to extend them so that for example a BigInt can be added to an int painlessly, see below:
int i;
BigInt I1, ... | I don't see why this needs to be a template:
template <class T> const BigInt operator+(const T& A, const BigInt& B)
{ return BigInt(A)+B; }
If you have a conversion from type T to BigInt, and you apperntly do, simply say:
const BigInt operator+(const Bigint& A, const BigInt& B)
{ return A+B; }
|
3,204,577 | 3,204,751 | Debug heap memory leak detection - strange results? | I think my C++ application is tight and doesn't leak any memory. Long running stress tests and static code analyzers seem to indicate as much. However, when exercising a very complex usage szenario the Visual Studio 2008 built in debug heap will show a couple of warnings like the following on exit:
Detected memory leak... | Seeing those "u" characters after the empty bracketed value is creepy. But looking at the CRT source code, that could be explained by a bug in the dumping code, it doesn't seem to zero-terminate the string when the memory block is 0 bytes (valbuff variable in dbgheap.c).
Allocating zero bytes is otherwise a supported ... |
3,204,776 | 3,204,909 | Which school of reporting function failures is better | Very often you have a function, which for given arguments can't generate valid result or it can't perform some tasks. Apart from exceptions, which are not so commonly used in C/C++ world, there are basically two schools of reporting invalid results.
First approach mixes valid returns with a value which does not belong ... | Don't ignore exceptions, for exceptional and unexpected errors.
However, just answering your points, the question is ultimately subjective. The key issue is to consider what will be easier for your consumers to work with, whilst quietly nudging them to remember to check error conditions. In my opinion, this is nearly a... |
3,204,871 | 3,205,057 | What's the best way to sum the result of a member function for all elements in a container? | Let's say I have the following object:
struct Foo
{
int size() { return 2; }
};
What's the best way (most maintainable, readable, etc.) to get the total size of all objects in a vector<Foo>? I'll post my solution but I'm interested in better ideas.
Update:
So far we have:
std::accumulate and a functor
std::accum... | In addition to your own suggestion, if your compiler supports C++0x lambda expressions, you can use this shorter version:
std::vector<Foo> vf;
// do something to populate vf
int totalSize = std::accumulate(vf.begin(),
vf.end(),
0,
... |
3,204,872 | 3,205,001 | How do I build all configurations of a Visual Studio 2008 C++ project on the command line? | I'd like to build all the configurations of a VS 2008 C++ project on the command line. Something like:
devenv TheProject.vcproj /build /nologo
But this doesn't work because the /build command insists on having a configuration following it like this:
devenv TheProject.vcproj /build "Release|Win32" /nologo
Is there a... | I was thinking you can do what you want with MSBUILD, but it appears that it isn't much better for this than DEVENV.
You still have to specify each configuration on the command line, although it would be easy to write a batch file to accomplish this with either MSBUILD or DEVENV.
It looks like previous versions of the ... |
3,205,197 | 3,205,275 | Remove environmental variable programmatically | I need to write a unit test for some C++ code that checks for the presence of an environmental variable. I'm using MSVS 2008 and gtest as my framework. I add the environmental variable using putenv, I check the environmental variable using getevn, but I can't figure out how to remove it so that no other test will see i... | Calling putenv again specifying "SOME_VAR=" as parameter will delete environment variable SOME_VAR. btw, Microsoft recommends using _putenv as putenv is deprecated.
|
3,205,242 | 3,205,324 | C++ basic constructor question | How should I handle the following situation :
I am writing my own 2D vector class and have the following code:
class Vector2 : public (...)
public:
Vector2(float x, float y) {
local_vector_storage_[0] = x;
local_vector_storage_[1] = y;
}
template <typename Iterator> Vector2(Iterator begin, Itera... | Something like this seems to work:
template<typename T>
struct notnumeric {typedef int OK;};
template<>
struct notnumeric<int> {};
class Vector2
{
public:
Vector2(float x, float y)
{
}
template <typename Iterator>
Vector2(Iterator begin, Iterator end, typename notnumeric<Iterator>::OK dummy = 0)
{
... |
3,205,423 | 3,207,864 | Listing certificates from a CAC without pin | I'm developing a CAC authentication app.
I'm running RHEL 5.5 and have a card reader attached to my machine. When I insert a smart card/CAC, there is a popup notification that comes on the upper right hand side on the window where the clock is and the "Smart Card Manager" GUI is accessible clicking on the icon (card wi... |
Search the web for "friendly certs" or "publicly readable certs" feature/mechanism (0x1<<28 when loading the module) - by default NSS assumes that a PIN is needed before anything can be read from the token. Which is IMHO utter stupidity and keeping it as a default...
Be sure to take into account pinpad readers (prote... |
3,205,442 | 3,207,600 | register for WindowServer CGScreenRefreshCallback CGScreenUpdateMoveCallback in C++ | I'm trying to register for CGScreenRefreshCallback and CGScreenUpdateMoveCallback ( here's what apple's saying about http://developer.apple.com/mac/library/documentation/GraphicsImaging/Reference/Quartz_Services_Ref/Reference/reference.html#//apple_ref/doc/uid/TP30001070-CH1g-F16970 )
using C++ only.
I wrote this simpl... | It's not about using/not using Objective-C. It's about the event loop in OS X apps in general, which is done by CFRunloop, which is a C API. See Run Loop management and CFRunLoop reference. You also need a connection to the window server, which can be established by calling
Instead of
while (true) {
// just hang... |
3,205,449 | 3,217,307 | using rake with project directory structure | I have been looking into Rake for build script in our CI system (Projects built with C++). I have been playing about with a simple 'hello world' application to see what rake is capable of doing. All was well until i decided to put the .h files into a include folder and the .cpp files into src folder. Rake was able to f... | this line: ALL_FILES = [C_FILES] + HDR_FILES should be ALL_FILES = C_FILES << HDR_FILES
a FileList is just a fancy array that rake provides for us, but it's just an array underneath the hood, so we can use all of the standard array operators on it.
the << operator will append all of the items in the HDR_FILES array o... |
3,205,493 | 3,205,657 | Write a client-server program in C ... on a sheet of paper | This was an actual interview question. o_O
Let's leave aside the issues of asking such a question in an interview.
I'm wondering what alternatives to the ol' TCP sockets approach are readily available (as libraries, for instance), for use in C or C++.
I'm making no assumptions on platform, compiler etc - take your pi... |
I'm making no assumptions on platform,
compiler etc - take your pick.
main() {
system("apache -start")
system("telnet 127.0.0.1 80")
}
;-)
|
3,205,552 | 3,207,817 | Passing temporaries as LValues | I'd like to use the following idiom, that I think is non-standard. I have functions which return vectors taking advantage of Return Value Optimization:
vector<T> some_func()
{
...
return vector<T>( /* something */ );
}
Then, I would like to use
vector<T>& some_reference;
std::swap(some_reference, some_func());... | Since std::vector is a class type and member functions can be called on rvalues:
some_func().swap(some_reference);
|
3,205,561 | 3,208,972 | binding generic c++ libraries to python with boost.python | I would like to know what's the process, when binding C++ libraries that are written with in a generic way.
Is there a posibility of binding a template class, or you can only bind only a template generated class ?
| You can only bind a generated class. However, it is possible to write a template function to export your class, and call this function for each concrete types you want to export. For example:
template<class T>
struct foo {};
template<class T>
void export_foo(std::string name) {
boost::python::class_<foo<T>>(name.... |
3,205,923 | 3,206,004 | Is there any way I can make g++ only emit warnings pertaining to my files? | I like to compile my code with -Wall, and sometimes even -pedantic. It's partly a style thing, and partly the fact that it does occasionally emit very, very useful warnings (such as using = rather than ==).
However, the writers of some of my headers are clearly not such sticklers. Compiling with either of the two warn... | Alternatively to JS Bangs' answer, you can have GCC treat them as system headers, which disables all warnings (excepting #warning directives) for those headers.
If the -isystem switch is unhelpful, you can wrap all of the offending headers with simpler headers that contain only the appropriate line:
#pragma GCC system_... |
3,206,157 | 3,208,929 | How can I resolve foo's library path using g++ -Lhere -Lthere -lfoo without building an object? | I would like to display the explicit path to a library which will be used in the linking stage of compilation. I want to do this so that I can add the library as a dependency to a separate object file.
In other words, I often link using:
g++ myFile.cpp -Lsomewhere -Lelse -Lhere -Lthere -lfoo
Is there a way to coerce g... | This isn't ideal, and I hope there is a cleaner answer, but you can get the default search paths from gcc, then search each one for the files. Here it is in GNU make:
libnams = foo bar
dirs = somewhere else here there
dirs += $(subst :, ,$(subst =,,$(word 2,$(shell gcc -print-search-dirs | grep libraries))))
exts = a s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.