question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,765,366 | 6,774,030 | Is there a quick way to switch the solution platform in Visual Studio 2010? | I want to compile my C++ projects in 32-bit and 64-bit mode. Until now, I created Solution Configurations: in addition to the pre-configured "Debug" and "Release" configurations, I then had "Debug x64" and "Release x64" configurations which I set to compile a project for the x64 architecture.
However, my latest projec... | There is a dropdown box for the target platform which can be added to the toolbar ("Project Platform"). This eliminates the need to encode the platform in Project Configurations.
|
6,765,657 | 6,765,690 | Linker Errors using directX and Visual Studio 2010 | So I've been working on this for the better part of two hours and although I appear to be following the exact instructions of every forum/guide on the internet, I'm still getting linker errors trying to use directX with Visual Studio 2010.
Here is the code I'm starting with:
#include <D3DX10.h>
#include <iostream> ... | Unless you use a special setting in Visual Studio, windowed executables start with the WinMain function, not the regular main function. So you should either be creating a console app, be using WinMain, or use the setting to use the regular main function.
Note that starting with WinMain is not required for actually crea... |
6,765,704 | 6,766,020 | Determine value of __PRETTY_FUNCTION__ prior to runtime execution | I'm currently using __PRETTY_FUNCTION__ when reporting messages (errors, warnings, etc) to a logfile. This ensures there is no confusion regarding which function created the error message.
At the moment, I would like to automatically take the output from the logfile and link it back up with the code which initially cre... | Using __LINE__ and __FILE__ is a simple and relatively easy solution. The changes to your log functions should be relatively minor in scope as well. If you want code coverage information you're probably better off using GCOV.
http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/index.html#toc_Gcov
http://bobah.net/d4d/tools/cod... |
6,765,770 | 6,765,787 | Compile-time assertion? | Is there a way I can assert that two constant expressions are equal at compile time?
e.g. I want this to cause a compile-time error
enum { foo=263, bar=264 };
SOME_EXPRESSION(foo,bar)
but I want this to not cause an error
enum { foo=263, bar=263 };
SOME_EXPRESSION(foo,bar)
edit: the above was simplified. My situati... | See static_assert (C++0x only); if on an older version, see Boost's StaticAssert.
|
6,765,948 | 6,766,317 | -march and debug mode | I know too much optimization doesn't make much sense for debug code.
But what about using -march=native to make better use of the instruction set?
EDIT:
Let's reformulate this. I know enabling optimizations and debug mode at the same time might have disadvantages like:
GCC allows you to use -g with -O. The shortcuts t... | The problem with optimization is aggressive optimization passes that alter control flow can confuse debuggers. -march=native may enable additional optimizations (cmov, for example) if those passes have been enabled with a -O option, but will not in itself confuse the debugger.
|
6,766,016 | 6,766,059 | How do I pass an entire array pointer as const such that the values cannot be changed? C++ | How do I pass an entire array pointer as const such that the values cannot be changed? I am passing in an array to a function like this:
double myArr[] { 1, 2, 3, 4, 5 };
double* pArr = myArr;
double myVal = MyFunc(pArr, 5);
MyFunc's header right now is:
MyFunc(double* pArr, int length)
I want to make sure that the... | Change your function signature to:
MyFunc(double const* pArr, int length);
Note that this is equivalent to:
MyFunc(const double* pArr, int length)
Which one you prefer is a matter of pure taste (I prefer the first, as I find it more readable -- it's the items in pArr that are const, not the pointer itself).
|
6,766,411 | 6,766,488 | What could be causing this memory access error (C++)? Might be undefined behavior? | I have a relatively large class that I'm working with and it's all worked fine so far (note: I didn't actually write the class, I'm just adding some functionality). However, after declaring one more string in the header file, everything now crashes (I get a memory access error). If I erase that string and rebuild, ev... | You've allocated some memory on the heap and failed to initialize it.
0xcd is a fill pattern used by the debug heap: before dynamically allocated memory is given to your program, it is filled with that pattern to help you find uninitialized variables.
As for why changing the class definition affects the outcome, you m... |
6,766,472 | 6,766,643 | using win32 in native applications | Is it necessary to use win32 in full native applications or it's good to use the visual mode of VC++ Express instead.
I want to know about the big programs like game engines that, are they using win32 to present their set of tools?
| Win32 API is basically a set of procedures to work with low level Windows objects like windows, controls, sockets and so on. So, if you say "native" that means that the only way you can do anything is using Win32 API.
Game engines are quite primitive from low level standpoint. Game engines are mostly algorithms, abstra... |
6,766,490 | 6,766,633 | Pointer to first byte of a vector<float> | The pointer to the audio buffer of the XAUDIO_BUFFER structure in XAudio2 is defined as BYTE *pAudioData. When I was using 16-bit Integer PCM, this is what my program looked like:
void buildWaveBuffer(std::vector<unsigned char> &vec)
{
std::string lineString;
int lineInt;
unsigned char lowByte, highByte;
... |
How do I give a pointer to the first byte in the vector?
The exact same way, but I'm not sure it will do what you expect. Read the comments to your question.
|
6,766,640 | 6,766,689 | How can I assign an instance variable without calling its constructor in C++? | Basically, I have a class called VisaMux and a class called MuxPath. MuxPath has a VisaMux private instance variable. I want MuxPath's constructor to assign the instance variable a given VisaMux object without invoking an empty VisaMux() constructor.
5 MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, cons... | Use the constructor initialization list:
MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux)
: clk_sel(Clk_sel)
, lane_sel(Lane_sel)
, mux(Mux)
{}
|
6,766,889 | 6,767,068 | C++ A polymorphic class, virtual function and casting for performance | I have the following classes:
class State
{
protected:
Vec3D accel;
Vec3D gyro;
Vec3D gps;
float reward;
public:
boost::ptr_vector<Action> actions;
...
virtual bool isTerm();
}
class guState : public State
{
float gps_stand_thres;
float gps_down_thres;
public:
guState(Ag... | The difference between static_cast and dynamic_cast is that an invalid static_cast is undefined behavior, while an invalid dynamic_cast results in a null-pointer or a bad_cast-exception (if you cast references). The penalty for a dynamic_cast is a type-check during runtime, and increased code-size due to RTTI.
So, if y... |
6,767,005 | 6,767,053 | Confused about C++ memory deallocation | So in C++ if I create an object useing new I should always deallocate it using delete
For example
Segment::Segment(float length)
{
segmentLength = length;
angle = 0.0f;
x = Rand::randFloat(1.0f, 1.5f);
y = Rand::randFloat(1.0f, 1.5f);
vx = Rand::randFloat(0.0f, 1.0f);
vy = Rand::randFloat(0.0... | Things not allocated with new, new[] or the malloc family should be destructed and "freed" when the object goes out of scope.
Often this simply means that that the code has reached the end of the block it was declared it or that the object that it was in was destructed (one way or another).
To see this in action, you c... |
6,767,085 | 6,767,695 | How to pass a C# double[] to a C++ function that requires constant double* pArr? C++, C# | I have a function in C++ written as:
MyFunc(const double* pArray, int length);
I need to pass a non-constant array into it:
//C#
double[] myDoubleArray = new double[] { 1, 2, 3, 4, 5 };
MyFunc(myDoubleArray, 5);
The program is breaking when I do this.
edit:
//C# declaration
[DllImport(@"RTATMATHLIB.dll", EntryPoin... | You can always pass a non-constant array to a function requiring a constant array. The const qualifier to the array implies that the function will not modify the contents of the array. The array does not need to be constant before passing to the function; the function will not modify the contents, due to the const in t... |
6,767,423 | 6,768,089 | What is the difference between Java's equals() and C++'s operator ==? | In a question regarding the use of typeid is C++, I suggested it could be used to compare types in objects comparison. I haven't seen it done much, but I had Java's equals in mind.
Looking into Java a bit more, this seems to be the case: Some say the actual classes of the two objects should be compared, and some say in... | In Java, all types ultimately derive from Object, and Object
defines a virtual function Object.equals(Object other), so you
can compare anything with anything else, regardless of whether
it makes sense or not. In C++, there is no univeral base, and
there is no implicit definition of ==. == is normally only
overridden... |
6,767,862 | 6,768,060 | What is a correct way of using an implementation with an interface class in C++? | I have a class Child and a class Human where Human has all the functions declared in Child as virtual functions. And a class Child inherits from Human class.
I want to use Human as a interface file to hide implementation in Child.
I didn't really set up a constructor, but I set up an init() function which initializes ... | You need to #include "Child.h" in your cpp file. You can do this along with including human.h or you can not include human.h as that will be brought in automatically by the include within child.h
#include <stdlib.h>
#include <stdio.h>
#include "Child.h"
#include "Human.h" // This is no longer necessary, as child.h ... |
6,768,025 | 6,768,130 | Why is it necessary to do a rebuild after adding a new member variable to a class? | This morning, in Visual Studio 2005, I tried adding a new private member variable to a class and found that it was giving me all sorts of weird segmentation faults and the like. When I went into debug mode, I found that my debugger didn't even see the new member variable, and thus it was giving me some strange behavio... | When you add or remove members of a class you change the memory layout of the object. If you don't recompile you are breaking the ODR rule, and the segmentation faults are just the effect of that.
As to why that happens, old code might be acquiring memory for the old size, and then passing that object (without the new ... |
6,768,300 | 6,768,324 | Can you call the arrow (->) operator function manually? | If I have a Foo *foo, I can say foo->bar(). Is it possible to call the operator->() function manually? And if so, how would I pass it bar()?
Does it make a difference if it is Foo foo instead?
Maybe something like foo.operator->(bar)?
| Yes, you can. With overloaded -> the foo->bar() expression is interpreted by the compiler as foo.operator->()->bar(). And this is exactly how you can call it "manually": foo.operator->()->bar().
If your overloaded operator -> function is implemented "properly", i.e. it returns something that also supports operator -> t... |
6,768,426 | 6,769,077 | In a signal handler, how to know where the program is interrupted? | On x86 (either 64-bit or 32-bit) Linux --
for example:
void signal_handler(int) {
// want to know where the program is interrupted ...
}
int main() {
...
signal(SIGALRM, signal_handler);
alarm(5);
...
printf(...); <------- at this point, we trigger signal_handler
...
}
In signal_handler, ho... | Use sigaction with SA_SIGINFO set in sa_flags.
Prototype code:
#define _GNU_SOURCE 1 /* To pick up REG_RIP */
#include <stdio.h>
#include <signal.h>
#include <assert.h>
static void
handler(int signo, siginfo_t *info, void *context)
{
const ucontext_t *con = (ucontext_t *)context;
/* I know, never call printf... |
6,768,453 | 6,831,475 | How do I safely share a variable with a thread that is in a different compilation unit? | In the structure of my program I've divided "where it gets called from" and "what gets done" into separate source files. As a matter of practicality, this allows me to compile the program as standalone or include it in a DLL. The code below is not the actual code but a simplified example that makes the same point.
Th... | I ended up removing the struct and replacing it with an object that encapsulates all the data. It's a little hideous, being filled with getters and setters, but in this particular case I'm using the access methods to make sure that locks are properly set/unset.
Using a void cast pointer to this object passed the objec... |
6,768,839 | 6,768,864 | expected duration between kill and the ability to reap with waitpid | I have a Linux app which must spawn a child process on request with one of the exec() functions.
If the child process has not finished before it's time to spawn it again, the app must kill the previous instance before starting the new one. It does this with
kill(pid, SIGTERM);
I'm keeping the pid of the previous inst... | The process may catch SIGTERM in order to perform its own cleanup before shutting down.
Even if it doesn't, you don't know how long it'll take the OS to shut down the process.
Trying to rely on things like this is a fool's errand.
|
6,768,885 | 6,768,990 | STL lower_bound not spec compliant | The following code doesn't compile in C++Builder 2009 or in Visual C++ 2005 when the macro _HAS_ITERATOR_DEBUGGING equals 1 but if commented out it will. It appears the lower_bound function isn't spec compliant. The library is swapping the arguments. Here's an excerpt form the spec. value should always be the second ar... | This is a known issue in the Visual C++ 2005 C++ Standard Library implementation (see "Binary predicate paramter to lower_bound assumes that both parameters are the same type when compiling in debug mode" on Microsoft Connect).
The bug was fixed in Visual C++ 2008.
|
6,768,927 | 6,769,013 | Looking for a function (or a macro) to return a boost::scoped_lock | I'm looking for code shortening idea. I'm using boost::scoped_lock to lock a boost::mutex but I want to shorten the amount of code I'm writing.
Currently I have a mutex defined in my class and the member field called _sync. When I want to lock, I have to write:
scoped_lock<mutex> lock(_sync);
The tricky part is that t... | #define LOCK(a) scoped_lock<mutex> scopedLockVar(a)
public void Object::modify()
{
LOCK(_sync); // <-- nice and short! ;)
// do something to modify the object
//..
// the mutex is unlocked when we leave the scope of modify
}
You should use a safe name for the define... The compiler just uses find and... |
6,769,068 | 6,769,109 | pygtkscintilla auto indent | I'm trying to translate the c++ code and i can't work out what "char linebuf[1000]" is, can some kind sole translate this to python or explain what linebuf is. Thanks! :) Taken from http://www.scintilla.org/ScintillaUsage.html
if (ch == '\r' || ch == '\n') {
char linebuf[1000];
int curLine = GetCu... | It is a buffer for a line of input text, of type char[1000], i.e. an array of 1000 char elements (which are actually bytes, because C++ is based upon C, which in turn predates the whole idea of character encodings).
If we really wanted a literal translation of the algorithm, the closest fit in Python is probably someth... |
6,769,142 | 6,770,043 | CUDA debugging procedure for non-deterministic output | I'm debugging my CUDA 4.0/Thrust-based image reconstruction code on my Ubuntu 10.10 64-bit system and I've been trying to figure out how to debug this run-time error I have in which my output images appear to some random "noise." There is no random number generator output in my code, so I expect the output to be consis... | Are you sure all of your kernels have proper blocksize/remainder handling? The one place we have seen non-deterministic results occurred when we had data elements at the end of the array not being processed.
Our kernels were originally were intended for data that was known to be an integer multiple of 256 elements. So ... |
6,769,237 | 6,769,671 | Should I have to create a thread if I want to make distributed mutex library? | I am trying to write a simple lock/unlock algorithm that behaves like a mutex in distributed systems with C++.
It will be implemented as a library and users will be able to use it using the interface file.
Assume there are 3 processes {A,B,C}.
Each processors knows other processes' addresses and ports and so on.
If A w... |
Should there be a separate thread for each processor running
listening(polling) to the sockets?
You should use a library for Inter-Process Communication, unless you intend to build something like that from scratch as an excercise. If you want to build something yourself, read that wikipedia article and maybe some c... |
6,769,411 | 6,769,461 | Having a problem with pass by reference in two dimensional array in c++ | I have a variable called names which is a two dimensional array.
I declared it like below so that there will be maximum of 5 names and each name will consist of 256 characters.
int main(){
char names[5][256];
strcpy(names[0],"John");
strcpy(names[1],"Matt");
printf("%d\n",sizeof(names)/256); //... | Your code is C-style. If you're really writing C++ then I suggest using std::cout, std::vector and std::string:
void passit(std::vector<std::string> const& names) {
std::cout << names.size();
}
int main() {
std::vector<std::string> names(5);
names[0] = "John";
names[1] = "Matt";
std::cout << name... |
6,769,416 | 6,769,623 | Difference between putback() and unget() | I'm using a Standard iostream to get some input from a file, and I'm confused about unget() versus putback(character). It seems to me from the documentation that these functions are effectively identical, where unget() just remembers the character put in, so I'm nervous. I've always used putback(character), but charact... | You can't lie with unget(). It "ungets" the last-read character. You can lie with putback(c). You can "putback" some character other than the last-read character. Sometimes putting back a character other than the last-read character can be useful.
Also, if the underlying read buffer really does have buffering capabilit... |
6,769,760 | 6,769,779 | How do files get into the External Dependencies in Visual Studio C++? | I wonder why one of my projects has VDSERR.h listed under "External Dependencies" and another hasn't and gives me an "undefined symbol" compiler error about a symbol which is defined in there. How can I include this file in the other project as well?
| The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).
You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its contai... |
6,769,875 | 6,769,899 | Trying to combine two similar printf style debug messages in to a single function | I have two printf style debug logging functions (DebuglogfA, DebuglogfB). Both operate the same way but one of the logging functions takes a logging level as a parameters and ignores low level debug messages.
Currently I duplicate the code for each of these functions but I would like DebuglogfB to be able to call Debu... | You could create a new function DebuglogfV which has const char *lpszText and va_list argList as parameters, and then let DebuglogfA and DebuglogfB call it to perform the actual logging.
|
6,769,881 | 6,770,329 | Emulate "double" using 2 "float"s | I am writing a program for an embedded hardware that only supports 32-bit single-precision floating-point arithmetic. The algorithm I am implementing, however, requires a 64-bit double-precision addition and comparison. I am trying to emulate double datatype using a tuple of two floats. So a double d will be emulated a... | double-float is a technique that uses pairs of single-precision numbers to achieve almost twice the precision of single precision arithmetic accompanied by a slight reduction of the single precision exponent range (due to intermediate underflow and overflow at the far ends of the range). The basic algorithms were devel... |
6,769,903 | 6,769,974 | Invalid conversion from const void* error | I am running the following code in an .mm file and I get the error:
Invalid conversion from 'const void*' to 'const __CFData*'
I need to run the code in .mm. If I change to .m it doesn't complain. Why is it behaving like this? I compile to iPhone
CFSocketNativeHandle native;
CFDataRef nativeProp = CFReadStreamCopy... | CFReadStreamCopyProperty() returns CFTypeRef, which is just a typedef for const void*, and C++ is stricter about conversions than C (or Objective-C). You need to cast explicitly here:
CFDataRef nativeProp = (CFDataRef)CFReadStreamCopyProperty(...);
|
6,770,149 | 6,770,187 | Creating an instance of a class with () | I have a question : what constructor is used when you create an instance of a class with ClassName instance() in C++ ?
Example:
#include <iostream>
using namespace std;
class Test
{
private:
Test()
{
cout << "AAA" << endl;
}
public:
Test(string str)
{
cout << "String = " << str <<... | Tricky! You would expect compilation to fail as default constructor is private. However, it compiles and nothing is created. The reason?
Test instance_1();
... is just a function declaration! (Which returns Test and takes nothing.)
|
6,770,236 | 6,772,037 | I tried: valgrind, _GLIBCXX_DEBUG, -fno-strict-aliasing; how do I debug this error? | I have a really strange error that I've spend several days trying to figure out, and so now I want to see if anybody has any comments to help me understand what's happening.
Some background. I'm working on a software project which involves adding C++ extensions to Python 2.7.1 using Boost 1.45, so all my code is being ... | You can change the type of floating-point data of your program. If you use float, you can switch to double; if c,f,df is double, you can switch to long double (80bit on intel; 128 on sparc). For 4.5.2 you can even try to use a _float128 (128bit) software-simulated type.
The rounding error will be less with longer float... |
6,770,258 | 6,770,275 | How do promotion rules work when the signedness on either side of a binary operator differ? | Consider the following programs:
// http://ideone.com/4I0dT
#include <limits>
#include <iostream>
int main()
{
int max = std::numeric_limits<int>::max();
unsigned int one = 1;
unsigned int result = max + one;
std::cout << result;
}
and
// http://ideone.com/UBuFZ
#include <limits>
#include <iostream>
... | This is outlined explicitly in §5/9:
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are de... |
6,770,287 | 6,770,310 | Working with a vector of a class | I am a newbie at C++, and I am just starting to work with the container called classes.
I am working on a program where an object is defined, and is stored inside a vector.
The program is as follows, and then the description of the error I got.
This is "car.h"
#ifndef CAR_H_GUARD
#define CAR_H_GUARD
class car{
i... | One uses delete only on things where one has used new. You never delete something that wasn't separately allocated by new. These lines in your Car destructor are... very destructive (pardon my pun):
delete &v;
delete &loc;
Delete these lines -- they're totally unnecessary and they're the source of your problem. Just a... |
6,770,409 | 6,770,422 | C++ Format for cout << Automatically | If I had a simple class with two variables, x and y, and a function ToString() that returns a formatted string with the data. When I call
cout << simpleClass << "\n";
anyone know a way I could have simpleClass.ToString automatically called to return the correctly formatted string? I'm guessing there's a way to do thi... | If you're asking how to define such an operator,
template<class CharT, class TraitsT>
std::basic_ostream<CharT, TraitsT>&
operator <<(std::basic_ostream<CharT, TraitsT>& os, SimpleClass const& sc)
{
return os << sc.ToString();
}
|
6,770,937 | 6,771,211 | C++ pass enum to object constructor | Say I have the following:
Foo::Foo() {
value = 25; //default constructor...
}
Foo::Foo(Enum bar) {
value = (int)bar; //purpose is to allow an integer to take enum constant's integer value.
}
from...
enum Enum
{
A = 25,
B = 50,
}
class Foo
{
public:
Foo();
Foo(Enum bar);
private:
int value;
}
Yet, if I do ... | It sounds like you forgot to link foo.C into your final application.
|
6,771,039 | 25,193,580 | Automatic Copy of Dependent Files in Qt Creator | I've build a program using Qt Creator 2.2.1 and Qt 4.7.4 (32 bit) whose output is an executable. Opening the exe using DependencyWalker it shows that the exe uses following DLLs:
KERNEL32.DLL
MSVCRT.DLL
MINGWM10.DLL
LIBGCC_S_DW2-1.DLL
QTCORE4.DLL
QTGUI4.DLL
I want after the build all dependent files (which may be dif... | In QT 5.3, you may be able to use the windeployqt qt tool to automatically copy the needed libraries.
The following additions to the project's .pro file should do the trick, but you might have to make some adjustments based on your particular situation.
isEmpty(TARGET_EXT) {
win32 {
TARGET_CUSTOM_EXT = .exe... |
6,771,274 | 6,771,288 | c++ equivalent to python append method for lists | I'm learning c++ coming from a background in python.
I'm wondering is there a way to append items to a list in c++?
myList = []
for i in range(10):
myList.append(i)
Is there something like this in c++ that you can do to an array?
| You need a vector, do something like this:
#include <vector>
void funct() {
std::vector<int> myList;
for(int i = 0; i < 10; i++)
myList.push_back(10);
}
See http://cplusplus.com/reference/stl/vector/ for more information.
|
6,771,374 | 6,771,418 | Sorting an STL vector on two values | How do I sort an STL vector based on two different comparison criterias? The default sort() function only takes a single sorter object.
| You need to combine the two criteria into one.
Heres an example of how you'd sort a struct with a first and second field
based on the first field, then the second field.
#include <algorithm>
struct MyEntry {
int first;
int second;
};
bool compare_entry( const MyEntry & e1, const MyEntry & e2) {
if( e1.first !... |
6,771,730 | 6,771,805 | Main in MFC console app (NOT WinMain, main) | For a sample program, though this is doing all good for me. But I was wondering how is it happening.
I created a console application with "MFC" checkbox enabled while creating the project (VC2008).
It created standard _tmain implementaion with AfxWinInit calls and all. Then I wrote my custom function Main and called it... | My test shows it goes to _tmain first, before custom Main.
|
6,771,790 | 6,771,835 | C++ file IO seeking to a specific line | for instance, I have this test.txt containing :
apple
computer
glass
mouse
blue
ground
then, I want to retrieve one random line from the text file.
here's my code :
ifstream file;
file.open("test.txt", ios::in);
char word[21];
int line = rand()%6 + 1;
for (int x = 0 ; x < line ; x++)
test.getline (word, 21);
cout... | Seed the random number as suggested by the comments above
#include <cstdlib>
#include <ctime>
#include <fstream>
//...other includes and code
ifstream file;
file.open("abc.txt", ios::in);
char word[21];
srand( time(NULL) );
int line = rand()%6 + 1;
for (int x = 0 ; x < line ; x++)
file.getline (word, 21);
cout <<... |
6,771,998 | 6,772,041 | dynamic_cast of void * | I need to use dynamic cast void*
void *target = (MYClass*)target;//I am storing initially(to implment delegate mechanism)
....
delegateClass *delegate = dynamic_cast<delegateClass*>(target);
It is giving error cannot convert void*, I cannot use below code... since it is a delegate mechanism
delegateClass *delegate = d... | You cannot use dynamic cast unless the original type of the variable had a vtable (ie, had virtual functions). This is because dynamic_cast requires run-time type information, which is recorded in the vtable; if the vtable is missing, the compiler doesn't know what type the object is.
You should declare a base class wi... |
6,772,345 | 6,772,453 | Call API in particular windows credentials | I want to call an API in particular Windows credentials,
One way is, write particular piece of code or API in another EXE and then execute the EXE in particular windows credentials. Please let me know if you are aware of any other solution.
Thanks in advance.
| You could use LogonUser(), then ImpersonateLoggenOnUser(), then call your code, then call RevertToSelf() to get back to the original credentials. You can do that either in your thread, or create a separate thread and do it there. The latter is preferred so that you have the thread exited after that and not skip the Rev... |
6,772,597 | 6,772,807 | The purpose of stdafx.h (And: Why doesn't this work?) | I am working on a project that has a vendor-provided API. I've made a class that uses that API in my project and I've included the vendors header file in my stdafx.h file. Things would not compile.
I then put the #include directly into my class' header file and now things compile (And yes, my class includes stdafx.h so... | stdafx.h is mainly used in the VS generated projects as the 'container' of headers to be precompiled.
When you added a new #include to stdafx.h it didn't get included because your project is probably configured to use precompiled headers, and when you add something to stdafx.h you need to regenerate the .pch file that ... |
6,772,802 | 6,772,887 | In C/C++, is there a directive similar to #ifndef for typedefs? | If I want to define a value only if it is not defined, I do something like this :
#ifndef THING
#define THING OTHER_THING
#endif
What if THING is a typedef'd identifier, and not defined? I would like to do something like this:
#ifntypedef thing_type
typedef uint32_t thing_type
#endif
The issue arose because I wanted... | No there is no such facility in C++ at preprocessing stage. At the max can do is
#ifndef thing_type
#define thing_type uint32_t
#endif
Though this is not a good coding practice and I don't suggest it.
|
6,773,057 | 6,773,089 | C++ - What is this doing if the constructor is private? | In the code below, why does the compiler not complain for mClass2?
class CMyClass{
private:
CMyClass(){}
};
void TestMethod(){
CMyClass mClass1; //Fails.
CMyClass mClass2(); //Works.
}
| Because you've just declared a function mClass2 of zero arguments that returns a CMyClass. That's a valid option since there could be, say, a static CMyClass instance which that function has access to. Note that CMyClass still has a public copy constructor.
(To convince yourself, compile this module to assembler and ob... |
6,773,122 | 6,773,252 | Qt - Visual Studio - Work with projects on multiple computers | I work with the same Visual Studio projects on multiple computers (work/home) using Dropbox to sync between the two. Because VS creates some extra large files, I used to remove the following before uploading to Dropbox:
Files = .pdb, sdf, .ilk .exe .tmp
Folders = ipch/, Release/, Debug/, GeneratedFiles/
Everything w... | I am not familiar with dropbox so I can't speak for what you do currently
What I like to do is to use a distributed versioning system (I use git) to look after the source code only. I use a .gitignore file to not version any object code and visual studio project files and the like. I can then clone these projects (wi... |
6,773,302 | 6,773,399 | Specialization of templated member function in templated class | I have a templated class with an templated member function
template<class T>
class A {
public:
template<class CT>
CT function();
};
Now I want to specialize the templated member function in 2 ways. First for having the same type as the class:
template<class T>
template<> // Line gcc gives an error for, see be... | Yes, this is the problem:
error: enclosing class templates are not explicitly specialized
You cannot specialize a member without also specializing the class.
What you can do is put the code from function in a separate class and specialize that, much like basic_string depends on a separate char_traits class. Then then... |
6,773,338 | 6,773,722 | Is it sane to use the Factory Pattern to instantiate all widgets? | I was looking into using the to implement the style and rendering in a little GUI toolkit of mine using the Factory Pattern, and then this crazy Idea struck me. Why not use the Factory Pattern for all widgets?
Right now I'm thinking something in style of:
Widget label = Widget::create("label", "Hello, World");
Widget b... | Pros
It would be easy to read widgets from file or some other external source and create them by their names.
Cons
It would be easy to pass incorrect type name into Widget::create and you'll get error in run-time only.
You will have no access to widget-specific API without downcasting - i.e. one more source of run-t... |
6,773,388 | 6,773,427 | How to get a 2d int array from a char*? | I want to pass a 2d int array into a main function.
Since the main function signature is like this
int main(int argc, char*argv[]
How can I get the 2d array into a int[][] in my code?
Command line:
myprogram {{2,3},{5,6},{4,5},{6,8},{2,5}}
| This: {{2,3},{5,6},{4,5},{6,8},{2,5}} will end up as a string in your program. You will need to break it up into pieces yourself to turn it into an array of arrays.
|
6,773,617 | 6,773,692 | Why compiler does not complain about accessing elements beyond the bounds of a dynamic array? | I am defining an array of size 9. but when I access the array index 10 it is not giving any error.
int main() {
bool* isSeedPos = new bool[9];
isSeedPos[10] = true;
}
I expected to get a compiler error, because there is no array element isSeedPos[10] in my array.
Why don't I get an error?
| Use std::vector instead. Some implementations will do bounds checking in debug mode.
|
6,773,723 | 6,773,798 | what does default constructor do when it's empty? | I wonder if anyone could explain what the default ctor does after memory allocated, how it initializes the allocated memory?
| I don't know which languange you asked the question for, but I will try to answer anyway for C++ and Java
In C++, it :
leaves the built-in types (int, float, pointers, etc.) to an uninitialized value
calls the default constructor on class members
In Java, I think all class members are initialized to their default va... |
6,773,734 | 6,773,748 | force key type of a std::map not to be const | C++ references tells us for a std::map
typedef pair<const Key, T> value_type;
Is it possible to force the Key Type not to be const ?
I need to do this in a template method like
template<class T> // T represent a map in general (std::map, boost::unordered_map or whatever..)
void foo(const T& m)
{
typename T::value_t... | No, it's not.
This is because map performs its internal ordering based on key. If you could modify the key yourself, willy-nilly, all hell would break loose.
You should use the provided API functions; where the use of one results in changing a Key value (actually I don't think that any do), the appropriate internal re-... |
6,773,786 | 6,773,844 | Why can I not call templated method of templated class from a templated function |
Possible Duplicate:
Confusing Template error
I have a templated class with a templated method.
Now I have another function, with 2 template arguments creating the class with the first template argument and calling the function with the second.
Consider this example:
template<class S>
class A {
public:
template<c... | A<T> is a dependent type (i.e. it depends on the template parameter T), so you have to specify that you're referring to a template member:
a.template f1<CT>();
|
6,773,818 | 6,774,127 | How to monitor c++ daemon process? | I develop one daemon tcp server with boost asio, I want to know is there any daemon manager lib to monitor the process, if the server process is dead, the manager can restart it
| You could try to use the very powerfull daemontools to manage everything. These tools allow very in grained monitoring, restarting etc.
If you don't need this power the following shell-script is often enough:
while true; do
$PROCESS
sleep $SLEEP_TIME
done
This takes care of restarting your system when it crashe... |
6,773,880 | 6,773,969 | Named sub-arrays of an array | I want to design a data structure with the following properties:
Accessible as a single array of some type say T. For example s[i].
Ability to access named ranges in it. For example s.GoodObjects[i], s.BadObjects[j].
Iterate over it as a whole (STL algorithms etc.).
Converting the name-index to index in the whole arra... | If you really want to to this, you could have a class storing several std::vectors and then supply an operator[] for the class itself that redirects into these vectors, perhaps depending on their respective size.
While you're at it, the outer class could also provide begin() and end() to allow iteration over the entire... |
6,773,990 | 6,774,393 | Save a Bitset into a Struct Field | I decedied not to use MACROS for the bitwise operations but rather use BitSet. Basically what i am intending to do is, I receive a struct evaluate its bits then appened them to another struct.
I receive a Struct, say:
typedef struct{
uint8 status; //!< Status
} MsgStatus;
I need to get the status and check each recei... | Use std::bitset's member function to_ulong, which returns the bits in the set as an unsigned long.
|
6,773,997 | 6,802,434 | Using mpl::vector to define boost::variant types | I'm using the library boost::variant to store a large number of types. As the number of type is growing, I will soon reach the limit of 20 types. In the documentation it seems possible to define the variant using a mpl::vector, which allows more than 20 types (up to 50 if I'm correct). I tried to replace my variant def... | Variant type definition is correct, the problem was due to a generic function in the program taking an arbitrary variant as parameter. Indeed, make_variant_over<mpl::vector<T0, T1, ...>> behaves like variant<T0, T1, ...> but is not the same type: it is a variant<over_sequence<vector<T0, T1, ...>>> (so T0 corresponds to... |
6,774,200 | 6,774,569 | Connecting a desktop application with a website | I made an application using Qt/C++ that reads some values every 5-7 seconds and sends them to a website.
My approach is very simple. I am just reading the values i want to send and then i make an HTTP POST to the website. I also send the username and password to the website.
The problem is that i cannot find out if th... | If the action performed completes before the response header is sent you have the option of adding a custom status to it. If your website is built on PHP you can call header() to add the custom status of the operation.
header('XAppRequest-Status: complete');
|
6,774,605 | 6,821,287 | Precise mode in Boehm Garbage Collector | I've read on the webpage of Mono that they are using the Boehm GC in precise mode. I too use the Boehm GC with C++, however, I have found nothing in its documentation or headers that would indicate a precise mode, much less how to turn it on.
Any information whether it actually has a precise mode by default and how to ... | The file doc/gcinterface.html from the garbage collector (archive here) states:
void * GC_MALLOC_ATOMIC(size_t nbytes)
Allocates nbytes of storage. Requires (amortized) time
proportional to nbytes. The resulting object will be automatically
deallocated when unreferenced. The client promises that the resultin... |
6,774,781 | 6,775,815 | Analyze Network events with xperf | I have written a small tcp-client/server-thing for testing the xperf-networkttrace capabilities.
But as it seems I did do something wrong with xperf.
When I use the Xperf kernel group NETWORK or DIAG+NETWORKTRACE it just shows me the "casual" stuff and nothin about tcp/udp-reads and writes...
Anyone got an clue of how ... | I found out, that the send and receive-actions are logged under the "Generic Events" section, as marks.
You can also find them "easily" if You post-process the etl-log into a human readable file and search for TCPRead/Write UDPRead/Write TCPDisconnect/Connect/Accept etc...
|
6,774,825 | 6,776,811 | Reading from ifstream won't read whitespace | I'm implementing a custom lexer in C++ and when attempting to read in whitespace, the ifstream won't read it out. I'm reading character by character using >>, and all the whitespace is gone. Is there any way to make the ifstream keep all the whitespace and read it out to me? I know that when reading whole strings, the ... | I ended up just cracking open the Windows API and using it to read the whole file into a buffer first, and then reading that buffer character by character. Thanks guys.
|
6,774,967 | 6,775,036 | LNK2019 unresolved external symbol NtOpenFile | I am facing linker error with my code. I am trying to compile with Visual Studio command Prompt (2010) in Win-7 X64 bit m/c.
The error which i see are as below.
dust2.obj
dust2.obj : error LNK2019: unresolved external symbol _NtOpenFile@24 referenced
in function _main
dust2.obj : error LNK2019: unresolved external s... | These functions cannot be called directly because they belong to internal API and are not exposed through any of the libraries. You need to obtain addresses of these function using GetProcAddress.
For more information look here.
|
6,775,090 | 6,775,374 | Using Boost.Phoenix's operator ->* | I'm playing around with Phoenix v3 trying to figure out whether we should standardize on it instead of the current mix of Bind and Lambda. From the documentation I got the impression that it should be possible to simplify some expressions.
Currently I'm stuck on the usage of the ->* operator in combination with the STL... | I am also not too good at phoenix but I think you cannot use the ->* operator the way you want it to use.
If you change your example to
...
vector<A*> va;
va.push_back(new A);
for_each(va.begin(), va.end(), bind(mem_fn(&A::f), arg1));
for_each(va.begin(), va.end(), (arg1->*&A::f)());
...
you will get ... |
6,775,174 | 6,775,268 | lambda: should capturing const reference by reference yield undefined behaviour? | I just found a nasty bug in my code because I captured a const reference to a string by reference. By the time the lambda was run the original string object was already long gone and the referenced value was empty whereas the purpose was that it would contains the value of the original string, hence the bug.
What baff... | Undefined behavior means there is no requirement what should happen. There is no requirement that it should crash. Whatever memory your dangling reference points at, there's no reason it shouldn't contain something that looks like an empty string, and it's plausible that the destructor of string leaves the memory in th... |
6,775,180 | 6,775,231 | Assigning heap objects to a std::map | This crashes at runtime.
std::map<std::string, MyClass> myMap;
myValue = new MyClass();
myMap["myKey"] = *myValue;
I have 2 requirements:
That instances of MyClass are held on the heap (hence use of new);
That I be able to reference these via an associative array (hence use of std::Map).
Why can I not use the derefe... | If you lose the scope of myValue then it's a memory leak. So it's better to store the MyClass* in your map.
std::map<std::string, MyClass*> myMap;
myValue = new MyClass();
myMap["myKey"] = myValue;
In given example, also make sure you delete the element while erasing or removing from the map<>. You can use smart point... |
6,775,336 | 72,104,469 | Does "explicit" keyword have any effect on a default constructor? | Is there a reason to use the explicit keyword for a constructor that doesn't take any arguments? Does it have any effect? I'm wondering because I just came across the line
explicit char_separator()
near the end of the page documenting boost::char_separator, but it's not explained any further there.
| Yes, it does have an effect.
Compare:
struct A
{
A() {}
};
void foo(A) {}
int main()
{
foo({}); // ok
}
and:
struct A
{
explicit A() {}
};
void foo(A) {}
int main()
{
foo({}); // error
}
|
6,775,394 | 6,775,492 | Copying a vector of pointers | I have a std::vector<A*> which I need to deep copy to another vector using A::Clone().
Instead of using handwritten loops, I was wondering whether I could use for_each or any Standard Library algorithm for this.
| The appropriate algorithm is std::transform and you can turn member function invocation into a unary functor with std::mem_fun
Example:
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>
class X
{
public:
X* clone();
};
int main()
{
std::vector<X*> vec1, vec2;
std::transform... |
6,775,587 | 6,775,863 | Using numeric_limits to default parameter values | I have a template statistics class that has range parameters.
template <typename T>
class limitStats
{
public:
limitStats(T mx, T min) :
max(mx),
min(mn),
range(mx-mn)
{;}
private:
const T max;
const T min;
const T range;
}
I would like to put default values of maximum and minim... | You might want to rethink your design. What are you trying to do with your limitStats that std::numeric_limits doesn't provide?
Don't replicate the badness of the design of std::numeric_limits. For example, std::numeric_limits<double>::min() is terribly misnamed. The minimum double is the additive inverse of the maximu... |
6,775,643 | 6,775,763 | allocating vectors (or vectors of vectors) dynamically | I need to dynamically allocate 1-D and 2-D arrays whose sizes are given at run-time.
I managed to "discover" std::vector and I think it fits my purposes, but I would like to ask whether what I've written is correct and/or can be improved.
This is what I'm doing:
#include <vector>
typedef std::vector< std::vector<doubl... | Dynamically allocating arrays is required when your dimensions are given at runtime, as you've discovered.
However, std::vector is already a wrapper around this process, so dynamically allocating vectors is like a double positive. It's redundant.
Just write (C++98):
#include <vector>
typedef std::vector< std::vector<d... |
6,775,873 | 6,776,681 | boost asio asynchronously waiting on a condition variable | Is it possible to perform an asynchronous wait (read : non-blocking) on a conditional variable in boost::asio ? if it isn't directly supported any hints on implementing it would be appreciated.
I could implement a timer and fire a wakeup even every few ms, but this is approach is vastly inferior, I find it hard to beli... | If I understand the intent correctly, you want to launch an event handler, when some condition variable is signaled, in context of asio thread pool? I think it would be sufficient to wait on the condition variable in the beginning of the handler, and io_service::post() itself back in the pool in the end, something of t... |
6,775,908 | 6,775,995 | Is text in code char or const char? |
Possible Duplicate:
String literals vs const char* in C
Why i can do this?
void foo(char * cstr) {
...
}
and in code
foo("some text");
shouldnt "some text" be of type const char * ?
if its char *, means i can modify it?
| Yes, it should be const.
In C++03, you are allowed to omit the const only for backward compatibility with C, but with two caveats:
You are still not allowed to modify the data. Yes, this is highly confusing. That's why leaving out const is deprecated. Ideally it would be plain disallowed (and, in C++11 onwards, it is)... |
6,776,213 | 6,776,316 | Reading in HEX number from file | This has me pretty bothered as I should be able to do it but when I read in the hex number and assign it to an unsigned int when I print it out I get a different number. Any advice would be great. Thanks
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream myfile;
myfile... | I bet you don't get a "different number".
I bet you get the same value, but in decimal representation.
You're already extracting a hex-representation value (myfile >> hex >> tester); now insert one, too (cout << hex << tester)!
|
6,776,304 | 6,776,546 | Algorithm to make numbers from match sticks | I made a program to solve this problem from the ACM.
Matchsticks are ideal tools to represent numbers. A common way to represent the ten decimal digits with matchsticks is the following:
This is identical to how numbers are displayed on an ordinary alarm clock. With a given number of matchsticks you can generate a wi... | In order to find the result :
first find the minimal number of digits for smallest number
then proceed from most significant digit to the least significant one.
Every digit should be chosen so that there exists a solution for remaining digits.
Each digit requires between 2 and 7 matches. So you must choose the smalle... |
6,776,324 | 6,776,349 | How to properly convert char* into std::string? (issues while using expat / std::string(char*)) | Problem Description
I'm using Expat with a custom C++ wrapper, which I already tested on other projects.
I'm running into problems, because the original data (c_str) is not converted to a std::string in the right way. This concers me, because I did not change the source of the wrapper.
It seems like the string gets nul... | Your pszData appears to be in some implementation-specific Unicode-derived format, where each "character" takes up two chars.
This means the source data is broken; it should have been a wchar_t buffer, perhaps.
|
6,776,622 | 6,776,730 | Using log4cxx with Visual Studio 2010. Application initialization error | I have succeeded to build the log4cxx library both in debug and release mode and created log4cxxd.lib and log4cxx.lib files. But when I try to use them with static linking in my visual C++ 2010 project I get
The application failed to initialize properly (0xc0150002).
in debug mode.
In release mode it just works fin... | Use the Dependency Walker on your application to determine what library is missing.
|
6,776,888 | 6,778,254 | wrapping a list of structs with boost.python | I have a C++ function that returns a list of structs. Inside the struct, there are more lists of structs.
struct CameraInfo {
CamName name;
std::list<CamImageFormat> lImgFormats;
std::list<CamControls> lCamControls;
};
std::list<CameraInfo> getCameraInfo()
{
std::list<CameraIn... | Does it have to be std::list ? If you use std::vector instead you can use boost::python::vector_indexing_suite to wrap the list. See this post for details.
If you must use std::list you'll need to create a helper class that wraps the std::list functionality with python's list methods. That can be quite involved, but... |
6,776,961 | 6,778,040 | How to inspect std::string in GDB with no source code? | I'm trying to debug a program that has no source code available, and I need to look at what it has stored in a std::string. I've been Googling and looking on here, and I've found some information about outputting STL containers, but all of it refers to variables, with no source or debug information all I have is a memo... | Every std::string implementation has a pointer to the raw characters in it somewhere. For g++ 4.x, that pointer is at offset 0 into the string.
If you know that the string resides at e.g. 0x7fffffffda88, then
print *(char**)0x7fffffffda88
is what you need.
|
6,776,967 | 6,777,811 | Parameters File to Store All Variables | Background: So I've created an application that is basically a large preference dialog where the user can configure a number of pages, each with a bunch of different settings. These settings are in the form of dropdowns and text boxes. I want to store all of the variables into one massive "Parameters.h" file so that I ... | The problem is that you're making the pages as local variables in CSAPrefsDialog::OnInitDialog, and those variables are destroyed as soon as you leave the function. You should make them as member variables of your CSAPrefsDialog class. Everything else you're doing looks fine.
|
6,777,236 | 6,777,432 | WinInet HttpQuery Info returning Invalid Status Codes | I am working on a program that needs to check the existence of a page before it loads (so nothing too exotic).
Everything is working OK, but I cannot get HttpQueryInfo to return a valid status code for a page. The status code returned is: 1875378224
Code producing the problem:
DWORD headerBuffSize = sizeof(DWORD);
DWO... | The information retrieved from the response header by HttpQueryInfo is always a text string.
int statusCode;
char responseText[256]; // change to wchar_t for unicode
DWORD responseTextSize = sizeof(responseText);
//Check existance of page (for 404 error)
if(!HttpQueryInfo(hRequestHandle,
HTTP_QUERY_... |
6,777,278 | 6,777,445 | What is the rationale for renaming monotonic_clock to steady_clock in <chrono>? | Why did the committee rename monotonic_clock to steady_clock?
Vendors are providing monotonic_clock for backwards compatibility so I expect monotonic_clock will linger for a while.
It just seems a bit early to deprecate something in C++0x. ;)
Edit: The committe has the right and responsibility to rename components the... | N3128 is the proposal that did so and includes the rationale:
The implementation of the timeout definition necessarily depends on a
steady clock, one that cannot be adjusted. A monotonic clock is not
sufficient. While one could be implicit in the standard, below we make
one explicit.
Given a steady clock, the mo... |
6,777,509 | 6,780,403 | Application interrupts like crazy | I had a perfectly running C++ (Android native) application .. then I introduced some try { } catch {} statements and if I debug the application it interrupts like crazy in random, correct pieces of code.
If I run the application it stops for an interrupt Zygote (app_process) complains about signal 2, which is SIGINT.
I... | Do a full rebuild. Your debug info may be off. That's the best answer one can give with the info in the OP.
|
6,777,606 | 6,777,652 | Question over the usage of rint | for(i = 0; i < 181; i++)
{
unsigned int index = rint(i/db);
assert(index >= 0 && index < data.ranges_count);
this->laser_ranges[i*2][0] = data.ranges[index] * 1e3;
}
what is the meaning of rint(i/db)? I am not sure how rint is used...
| rint is a function that rounds a floating point number to an integer. It is a non-standard function. If db is of an integral type, then i/db will truncate to an integer and the code will not work as you have expected. Otherwise the rint(i/db) is i/db rounded to the nearest integer.
As to why the rounding is needed here... |
6,777,863 | 6,778,019 | Is it possible to implement a small Disk OS in C or C++? | I am not trying to do any such thing, but I was wondering out of curiosity whether one could implement an "entire OS" (not necessarily something big like Linux or Microsoft Windows, but more like a small DOS-like operating system) in C and/or C++ using no or little assembly.
By implementing an OS , I mean making an OS... | Obligatory link to the OSDev wiki, which describes most of the steps needed to create an OS as described on x86/x64.
To answer your question, it is gonna be extremely difficult/unpleasant to create the boot loader and start protected mode without resorting to at least some assembly, though it can be kept to a minimum ... |
6,777,884 | 6,778,038 | QStringList remove spaces from strings | What a best way for trimming all strings in string list? I try to use replaceInStrings:
QStringList somelist;
// ... //
// add some strings
// ... //
somelist.replaceInStrings(QRegExp("^\s*"),"");
but spaces not removed.
| As another answer already told, you need to escape the backslash. You also want to change the expression to match one or more spaces and not 0 or more spaces, try using:
QRegExp("^\\s+")
|
6,777,887 | 6,786,120 | Luabind: return_stl_iterator for std::map | Is there any way to return an STL iterator to a std::map (e.g. std::map<const std::string, int>)?
Luabind definition for an example class:
class_<SomeClass>( "SomeClass" )
.property( "items", &SomeClass::GetItems, return_stl_iterator )
GetItems() returns a const reference to a std::map container.
When accessing it i... | After browsing the source code I discovered that the Luabind return_stl_iterator policy only supports iterators that reference the wanted datatype directly. Iterators for associative containers are not supported (first and second are never accessed).
|
6,778,021 | 6,780,660 | Optimizing composite std::functions | Is it possible to optimize a series of "glued together" std::functions and/or is there any implementation that attempts to do this?
What I mean is most easily expressed mathematically: say I want to make a std::function that is a function of a function:
f(x,y,z) = x^2 * y^3 * z^4
g(x,y,z) = f(x,y,z) / (x*y^2)
Is there... | This is why you leave the optimizing to the compiler. They're algebraically equivalent but not equivalent due to FP imprecision. Your two versions of g would yield subtly different answers, which could be very important if called in an inner loop- not to mention the behavioural difference if x, y, z was 0.
Secondly, as... |
6,778,078 | 6,778,578 | Unit Testing legacy C++ Code with CPPUnit | I am tasked with managing a large code base written in vc++ 6.0, I need to start building unit test for portions of the code. I have set up CPPUnit and it works with my projects DLL's the problem I am facing is as follows. The legacy application is made up of 10 static libraries and one huge executable MFC application ... | You should carry on as you are:
You have one test application that references libraries.
You have one main application that also references those libraries.
Either move code from the main application into the existing libraries, or, preferably, move code into new libraries. Then your test application can access more... |
6,778,210 | 6,794,598 | unknown type name namespace in xcode (Awesomium) | Why does Xcode insist on "Unknown type name 'namespace'" in this C++ header ?!!
Bascially i am trying to use "Awesomium" http://awesomium.com/ sdk in my mac application and i keep getting
"Unknown type name 'namespace" in their hearder files
#ifndef __KEYBOARDCODES_H__
#define __KEYBOARDCODES_H__
namespace Awesomium... | If you wish to use Awesomium with Objective-C, you will need to use the ANSI C API instead. More information: http://support.awesomium.com/kb/wrappers-integration/ansi-c-api
If you have any other questions, please drop us a line in our support forum: http://support.awesomium.com
|
6,778,222 | 6,778,299 | Link imports by name (C++/Visual Studio) | I have a few NT imports I want to use in my program, problem is I am unable to use them without going though the lengthly process of downloading and setting up the WDK to use just two functions. I would also prefer not to use GetModuleHandle and GetProcAddress.
I know in VB6 you can manually define imported functions f... | You say you don't want to use GetProcAddress, but that's exactly what VB6 Declare Function (and .NET p/invoke) does.
You do need a complete prototype, often you can recreate enough of the header file from documentation.
The import library is a little more difficult, but there are tools to create import libraries from t... |
6,778,375 | 6,778,892 | Reading config files with C++ |
Possible Duplicates:
C++ Read Lines from File
File based Configuration handling in C ( Unix )
Using C++ how can I extract data for int id; string name; char mac[6]; from a configuration file: config.txt. Contents of which are for example:
ID 34
Name BUZINGA
MAC 0x67:0x45:0x4d:0x5d:0xcc:0x13
| First, search the web and Stack Overflow for the keywords "parsing" and "file". To narrow your search, add the keywords "mac address c++".
Next, prefer to read data into memory than process memory. In other words, read a line of text into a string and use methods of std::string for finding items in the text.
Research... |
6,778,478 | 6,778,500 | Are multiple sequential array access optimised? | Will C++ compilers automatically optimise the following code to calculate 3*i only once, and increment the result, or must the programmer code this?
void writeToArray(int i, int a, int b, int c)
{
array[3*i][1]=a;
array[3*i][2]=b;
array[3*i][3]=c;
}
| When you enable optimization, almost all compilers will not only precompute the common index 3*i but the pointer array + (3*i)*sizeof (*array).
|
6,778,496 | 6,778,726 | How can I test private members and methods of classes? | I am trying to do unit testing (using the Boost unit testing framework) on a C++ class called VariableImpl. Here are the details.
class Variable
{
public:
void UpdateStatistics (void) {
// compute mean based on m_val and update m_mean;
OtherClass::SendData (m_mean);
m_val.clear ();
}
virtual void Reco... | Well, unit testing should test units and ideally every class is a self-contained unit – this follows directly from the single responsibility principle.
So testing private members of a class shouldn’t be necessary – the class is a black box that can be covered in a unit test as-is.
On the other hand, this isn’t always t... |
6,778,941 | 6,780,969 | Two way communication with (static) library | I am writing a program, the bulk of which is platform independent code compiled as a static library. I am then writing a program using any specific platform apis which is linked to the static library. Calling functions in the library from the actual program is obviously easy, however I am unsure of the best way (most e... | Here are your options from (roughly) most flexible to least:
Signals & slots
Several signals and slots implementations are listed here (notably Boost.Signal). These are useful to implement the Observer design pattern where more than one object is interested in receiving notifications.
Boost.Function
You can register a ... |
6,778,978 | 6,779,529 | OpenGL transparent effects displayed quite awful on Meego | we've been creating several half-transparent 3D cubes in a scene by OpenGL which displays very good on Windows 7 and Fedora 15, but become quite awful on Meego system.
This is what it looks like on my Fedora 15 system:
This is what it looks like on Meego. The color of the line has been changed by us, otherwise the cub... | It sounds as if you may be relying on default settings (or behavior), which may be different between platforms.
Are you explicitly setting any of OpenGL's blend properties, such as glBlendFunc? If you are, it may help to post the relevant code that does this.
One of the comments mentioned sorting your transparent obje... |
6,779,058 | 6,903,285 | problem with shadow volume using opengl | I cannot figure out a solution to my shadown projections using
shadow volumes and stencil buffers. The problem can be viewed in:
www.dt.fee.unicamp.br/~ricfow/shadowProblem.avi
In this other video:
www.dt.fee.unicamp.br/~ricfow/shadowProblemAux.avi
only the faces associated to the silhouettes have been draw,
where blue... | Problem solved. Some edges beloging to the silhouettes were being extruded twice. Thanks.
|
6,779,179 | 6,798,438 | Assigning a value to a pointer | If I have the following for example:
int *x;
x = func(a);
For the statement: x = func(a);, do we say that we are returning an address to x? Or, how exactly do we read it?
EDIT: Is it eligible to say that we are returning a pointer to x? If so, can you explain how this is done exactly? I mean, how are we returning a po... | x is a pointer, specifically to an int. So it should be obvious that there are two memory locations used. One for the pointer and one for the memory it's pointing to (assuming the pointer is not null).
The pointer itself holds a memory address, specifically the location of the memory it's pointing to. Something li... |
6,779,386 | 6,780,000 | SendMessage vs PostMessage + WaitForSingleObject | I was wondering what's the difference between calling SendMessage (which blocks) and calling PostMessage in conjunction with WaitForSingleObject.
Thoughts?
| SendMessage() may be denied, if you call it from within the context of a COM call, where the COM object lives in an STA (calls are dispatched through the message pump). PostMessage() is not restricted to adhere to COM apartment rules.
Also, PostMessage() puts the message on the end of the window's message queue. SendMe... |
6,779,645 | 6,779,684 | Use of "this" keyword in C++ |
Possible Duplicate:
Is excessive use of this in C++ a code smell
When should you use the "this" keyword in C++?
Is there any reason to use this->
In C++, is the keyword this usually omitted? For example:
Person::Person(int age) {
_age = age;
}
As opposed to:
Person::Person(int age) {
this->_age = age;
}
| Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:
Person::Person() {
int age;
this->age = 1;
}
Also, this:
Person::Person(int _age) {
age = _age;
}
It is pretty bad style; if you need an initializer with the sa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.