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,119,354 | 6,119,397 | Extract 2bytes (u_short) from pointer | I have a pointer and I want to assign the bytes from x to (x+1) to a unsigned short. I was hoping that I could just
(unsigned short) pointer[x]
but the first byte seems to always be empty. But when I check the value of bytes x and x+1 individually the data is there.
Where have I noobed? (I just made it a verb)
| unsigned short i = (pointer[x] << 8) + pointer[x+1]
Assuming you want x to be the high bits and x+1 to be the low bits. Actually, you should keep endianness in mind here too.
EDIT:
This may also work:
*(unsigned short *) pointer[x]
However, this will be affected by endianness, for example, in little endian the firs... |
6,119,496 | 6,119,615 | Selecting the right equality operator when using templates | im trying to write a uint128_t library (http://stackoverflow.com/questions/6119306/operator-overloading-c-placement) and ive hit a bump: i need to operate on different types of ints, such as uint128_t ^ uint64_t. i have written the operator overloads such as template <typename t> uint128_t operator^(T val). i also need... | You shouldn't even need the extra overloads for anything other than the conversion constructors. Then you just write the operators that handle uint128_t, and if you try to pass another convertible type, such as an int, it will be converted using the conversion constructor, then the appropriate operator will be called.... |
6,119,602 | 6,119,624 | How does &x vary from x if x is a pointer? | So...I have the following code:
int main(void)
{
const char *s="hello, world";
cout<<&s[7]<<endl;
return 0;
}
and it prints "world"...however I don't understand why this:
int main(void)
{
const char *s="hello, world";
cout<<s[7]<<endl;
return 0;
}
only will print "w" (all I changed is got rid of the ampersand), bu... | s[7] is the character 'w', so &s[7] becomes the address of the character 'w'. And when you pass an address of char* type to cout, it prints all characters starting from the character to the null character which is end of the string i.e it continues to print characters from 'w' onward till it finds \0 . That is how worl... |
6,119,664 | 6,121,191 | How to use pthread_mutex and it's functions within a class? | I have searched for many hours for a solution, but cannot find an easy answer.
I got a class, which uses pthreads. The actual function pointer is static within the class, and I need to lock on a mutex, because so far I get "weird" results (parameters not being passed correctly).
However the pthread_mutex_lock and unloc... | By 'doesn't work' I assume you mean it won't compile since you're trying to use an instance member in a static member function.
But the bigger question is why are you trying to use threads for this?
The thread function you have is entirely protected by the mutex anyway - you'll get the same (or better) performance b... |
6,119,701 | 6,599,640 | Qt 4.7 using Eclipse on windows? | Has anyone had luck getting Qt Eclipse integration working on windows?
Here is what I did, to no avail:
Download latest Qt SDK, and install.
Download the Eclipse for C/C++ developers bundle, and install.
Download latest Qt/eclipse integration. (Not so new... http://qt.nokia.com/developer/eclipse-integration/ )
At th... | So, it turns out that Qt is no longer really putting any effort to support Eclipse. They want to push Qt Creator.
The plugin has not been updated for a long time.
|
6,119,772 | 6,119,810 | Face Detector Parameters for OpenCV cv_haar_scale_image | What does cv_haar_scale_image do in opencv's function cvhaardetectobjects?
| The flag CV_HAAR_SCALE_IMAGE, tells the algorithm to scale the image rather than the detector.
There is an example of its use here: Face detection: How to find faces with openCV
|
6,119,816 | 6,120,303 | Is there any comparable alternative to Qt? | I love the idea of Qt, however I use it not only for open source but closed source development. This isn't a real problem because I just license under the LGPL and distribute the DLLs needed. I've run into a problem though unfortunately.
The compiled statically linked executable is 4.36 MB. Not too shabby.
The compil... | Why don't you wrap all the functionality you need in a separate statically compiled dll and link your program dynamically with that. You can release the source code of the statically compiled dll since it's just a wrapper. And overall you'll still comply with LGPL.
|
6,119,862 | 6,120,215 | C++ DLL Function Export. DLL does not stay loaded | hi I've got the following problem, and I cannot figure out what is going on.
DLL code mylib.cpp (mylib.dll):
#include <Windows.h>
#include <tchar.h>
__declspec(dllexport) LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) {
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
BOOL WINAPI Dll... | Two things:
Don't assume that DLL_THREAD_ATTACH means things are going wrong. It's something that should happen when something links to your DLL as c-smile said.
Since this is a C++ compilation unit, your export will have the mangled name ?HookProc@@YGJHIJ@Z - that's why GetProcAddress(hInstDLL, "HookProc") fails - i... |
6,119,927 | 6,119,971 | Empty Base Optimisation MSVC | Empty base optimisation with multiple inheritance appears still to be broken in msvc++ 2010. Currently, it appears to only work for the first type derived from, so if you are deriving from multiple empty bases the child type ends up with more bytes (just useless padding!) than it needs.
Apparently it's been this way fo... |
Empty base optimisation with multiple inheritance appears still to be broken in msvc++ 2010
What do you mean by "broken"? That, it is not Standard conformant?
The Standard doesn't require empty classes to have zero size when deriving from them. An implementation may choose to optimize this or it may not at all.
|
6,120,000 | 6,120,462 | Do STL predicates need to be pure predicates? | By "pure" predicates I mean they only depend on their arguments. So is the following function object a valid predicate for use in say, std::sort
// A predicate for sorting objects of type T2 that relies on an
// object of type T1.
class APredicate {
T1 &someObj;
APredicate(T1 &someObject) : someObj(someObject)... | The "only depends on their arguments" actually means "if called again with the same arguments, must return the same result as previously". If your (particular instance of) someObj does not change it's mind on what to return from someObj::someFn for particular instances of T2 it is "pure".
As long as the condition holds... |
6,120,228 | 6,120,317 | Assignment operator and copy constructor in the presence of references | I am just experimenting with the references using this code:
class A
{
};
class B
{
public:
B(A& a): m_a(a){}
A& m_a;
};
int main()
{
A a;
B b(a);
B b1 = b;
}
I was expecting both B b1 = b; to produce a error. Instead when I compile with VS2008 I just get a warning
warning C4512: 'B' : assign... | warning C4512: 'B' : assignment operator could not be generated
Question 1: Why this warning?
References can only be initialized once when they are created. You cannot reassign a reference to another same type variable after creation because Reference is just an alias of the type variable for which it was created and ... |
6,120,240 | 6,120,334 | Why constructor is not called for given casting operator? | struct A {};
struct B
{
B (A* pA) {}
B& operator = (A* pA) { return *this; }
};
template<typename T>
struct Wrap
{
T *x;
operator T* () { return x; }
};
int main ()
{
Wrap<A> a;
B oB = a; // error: conversion from ‘Wrap<A>’ to non-scalar type ‘B’ requested
oB = a; // ok
}
When oB is constructed then... | The problem is that the number of user-defined conversions that are invoked implicitly is limited (to 1) by the Standard.
B ob = a;
implies two user conversions:
on a: Wrap<A>::operator A*() should be called
on the result: B::B(A*) should be called
@James Kanze's explanation: this syntax is called "copy initializati... |
6,120,348 | 6,120,402 | A point from C++0x draft : n3290 | A point from N3290 draft ISO Standard, §3.4.1/12:
During the lookup of a name used in the constant-expression of an enumerator-definition, previously declared enumerators of the enumeration are visible and hide the names of entities declared in the block, class, or namespace scopes containing the enum-specifier.
This ... | Let's just have some code:
struct X {};
enum Foo
{
X = 0,
Y,
Z = X // X refers to the enum, not the type
};
|
6,120,351 | 6,120,436 | why am I getting a "was not declared in this scope" error? | I get 5 errors at the following snippet of code
4 of the errors are
expected unqualified-id before '('
token|
and 1 error
'GetEntityIterator' was not declared
in this scope|
GetEntityIterator() returns vector<*Entity>::iterator EntityIterator
GetAABB() returns an AABB
I can post more code if needed
void ... | Maybe because of this syntax:
getEntityManager()->(*GetEntityIterator())
?
I'm not sure what you were trying to do, but the -> operator is supposed to be followed by the name of a member of the class.
Edit
After reading iaamilind's comment, I finally think I understand what you were trying to do. You were trying to de... |
6,120,382 | 6,122,531 | comparing with namespace variable | i am using namespace in header file as under
namespace MyNameSpace
{
extern string data;
};
And in implementation file as under.
namespace MyNameSpace
{
string data = "Data";
};
Then in some point of my code i am comparing as under.
string mData = "Data";
if(mData == MyNameSpace::data)
{
//do someth... | I cannot definately be sure that this is causing your particular problem because I do not know the rest of the code. However, it should definately apply anyway:
From the Google C++ Style Guide:
Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of constructi... |
6,120,497 | 6,128,867 | QCA QtCrypto in QT Problem | I had just imported a downloaded files (qca-2.0.1-mingw) through my project and successfully imported it into my project.
My Problem is now this:
How could i use the encryption and decryption function of QCA.
I had found this link but whenever i added this code to my codes my project doesn't run at all.
| You need to link against the QCA lib, did you do that? (I'm not sure what you mean by "imported the files").
If you follow the installation steps inside the README/INSTALL file which comes with QCA you should just be able to add this to your Qt project file to link against QCA:
CONFIG += crypto
Or you can still add th... |
6,120,798 | 6,120,812 | STL Container default Initialization | Hello
I have following struct
struct node {
std::string word
std::vector<struct node *> child;
}
When I create the new node, I have no way to initialize child vector.
What I essentially want is to check any element using operator[] is there is valid value.
I want to do following
if ( nodeptr->child[5] ) {
}
B... | In this case you would have to provide a constructor for you struct.
struct node {
node() : word(), child(10, NULL) {}
std::string word
std::vector<struct node *> child;
}
This will initialize the vector with 10 NULL-pointers. You can then check if an index is NULL (meaning it does not contain data), or not (... |
6,120,841 | 6,121,101 | Is it possible to write auto-cast operator outside a struct? | The exact situation is next:
I have defined in system API structs CGPoint and CGSize, and I want to be able to write my_point = my_size.
I can't modify CGPoint struct, only can write external operator. I can write binary operators (+, -, ...) but operator= must by declared inside struct. So is there any other solution?... | To make the expression a = b; compile you need to either have an operator= in the type of a that takes an element of the type of b, or a type implicitly convertible from b.
The first case is ruled out, since operator= must be a member of the class, and since you cannot modify GLPoint then you cannot add GLPoint& GLPoin... |
6,120,854 | 6,121,467 | How can I maintain a weak reference on a COM object in C++? | In my application, I'm hooking various functions for creating COM objects (such as CoCreateInstanceEx) to get notified whenever some object is created. I'm keeping track of all created objects in a std::list and I'm iterating over that list to do various things (like checking which OLE objects have been activated).
The... | This isn't an answer as much as a set of issues why this is a really tricky thing to do - I'm putting it in as an answer since there's too much information here than fits in a comment :)
My understanding is that the concept of weak reference just doesn't exist in COM, period. You've got reference counting via IUnknown,... |
6,121,082 | 6,121,116 | Convert C# to unmanaged C++ | I have the unenviable task of converting a couple of C# (CCW) COM servers (one is an Activex Control) to unmanaged C++. Any suggestions on tools I could use to make this as easy as possible would be gratefully accepted.
| Tangible Software sells a C# to C++ converter, but I've never used it myself...
http://www.tangiblesoftwaresolutions.com/Product_Details/CSharp_to_CPlusPlus_Converter_Details.html
|
6,121,287 | 6,121,308 | Compute 5 to the power of 3, but it returns 0. Why? | #include <iostream>
double power (double z, int n)
{
double result(0.0);
for (int i = 1; i <= n; i++)
result *= z;
return result;
}
int main()
{
int index(3);
double x(5.0), double y(0.0);
y = power (x, index);
std::cout << y << std::endl;
return 0;
}
Hello, where is the mista... | Because result is initialised to 0. And as we know, 0 * anything == 0. You need to start at 1.
[In future, please learn how to debug! You would easily have spotted this if you had stepped through your code in a debugger, or added some printf statements to your function.]
|
6,121,530 | 6,121,590 | function objects and constructors | I was just reading this
class biggerThan
{
public:
const int testValue;
biggerThan(int x) : testValue(x) { }
bool operator()(int val) const
{ return val > testValue; }
};
Now say its used like
std::list<int>::iterator firstBig =
std::find_if(aList.begin(), aLi... | Maybe the following code will make it clear:
#include <iostream>
#include <algorithm>
class biggerThan
{
public:
const int testValue;
biggerThan(int x) : testValue(x) {
std::cout << "Construction of biggerThan object with value "
<< x << std::endl;
... |
6,121,545 | 6,121,569 | Variable was not declared in this scope? | I'm getting this error in several methods for several variables (all of which are vectors):
error: ‘parent’ was not declared in this scope
I've tried wrapping my method implementations inside of "namespace DisjointSubsets { ... }", but that causes other problems. It seems to only do this for vectors, and I've tried ad... | You must use std::vector<unsigned> instead of just vector<unsigned> to declare parent because vectoris declared in the std namespace.
Therefore you could also use using namespace std; before declaring the class.
However most people I know would discourage you from using the second form in a header file.
See the C++ FAQ... |
6,121,623 | 6,121,690 | Catching exception: divide by zero | The following code does not catch an exception, when I try to divide by 0. Do I need to throw an exception, or does the computer automatically throw one at runtime?
int i = 0;
cin >> i; // what if someone enters zero?
try {
i = 5/i;
}
catch (std::logic_error e) {
cerr << e.what();
}
| You need to check it yourself and throw an exception. Integer divide by zero is not an exception in standard C++.
Neither is floating point divide by zero but at least that has specific means for dealing with it.
The exceptions listed in the ISO standard are:
namespace std {
class logic_error;
class domain_... |
6,121,758 | 6,121,790 | What's the meaning of #define when there is only 2 part? | I know the following 3 parts #define:
#define PI 3.4
which mean it will replace PI with 3.4.
But that's the meaning of 2 parts #define like this:
#define something
Will it replace something with null/empty string?
The following is the code example, I searched the file, only list the related lines
D:\mariadb\storage... | Yes it meaning replace something with an empty string. But the important thing is now something is recognized by the preprocessor that it is "defined", so
#ifdef something
will pass after that #define (Line 172).
Also, it is common to use it for configurational or vendor-specific attributes (Line 325, ...), like
#if M... |
6,121,792 | 7,495,023 | How to check if a CPU supports the SSE3 instruction set? | Is the following code valid to check if a CPU supports the SSE3 instruction set?
Using the IsProcessorFeaturePresent() function apparently does not work on Windows XP.
bool CheckSSE3()
{
int CPUInfo[4] = {-1};
//-- Get number of valid info ids
__cpuid(CPUInfo, 0);
int nIds = CPUInfo[0];
//-- Get i... | I've created a GitHub repro that will detect CPU and OS support for all the major x86 ISA extensions: https://github.com/Mysticial/FeatureDetector
Here's a shorter version:
First you need to access the CPUID instruction:
#ifdef _WIN32
// Windows
#define cpuid(info, x) __cpuidex(info, x, 0)
#else
// GCC Intrins... |
6,122,091 | 6,122,170 | Whats the difference? Pointer to an array vs regular array | I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials here. I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
If you
want to be able to alter the size of
... | int array[10]; declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using delete [] on that kind of array, in fact, you might crash the program if y... |
6,122,280 | 6,122,307 | How do I transfer this c ++ for loop into java for loop | I am a newbie C++ and I want to convert this line of for loop code into java version
for(;diff;diff++){
do something here
}
diff is an integer type variable.
Thanks in advance.
| The issue is that C allows an implicit conversion from int to boolean for the termination condition whereas Java doesn't. Try
for(; diff != 0; diff++)
{
which should be equivalent.
|
6,122,754 | 6,122,787 | Java math conversion | I have this code in C++
float result = -log(result)/0.5231-1.0;
And I converted that into Java code like this
float result = (float) (-Math.log(result)/0.5231-1.0);
Is this correct way to convert the c++ code?
| Well, the first C++ statement is illegal. You are defining result, and while initializing you use result.
But yes, the Java code does the same as the C++ code, if we ignore the irrelevant errors.
|
6,122,797 | 6,180,575 | Phonetic characters to speech | My purpose is that to be able to let my application to talk in less popular language (for example Hokkien, Malay, etc). My current approach is using recorded mp3.
I want to know whether there is 'phonetic characters to speech' engine exists for .net or any platform?
Phonetic characters here just like the phonetic entry... | Here is the VB.NET code:
'create the object. This object will store your phonetic 'characters'
Dim PBuilder As New System.Speech.Synthesis.PromptBuilder
'add your phonetic 'characters' here. Just ignore the first parameter.
'The second parameter is your phonetic 'characters'
PBuilder.AppendTextWithPronunciation("test"... |
6,122,864 | 6,123,207 | windows forms, how to launch a separate window with datagridview? | I've some data that can be shown on grid attached on a panel. When user clicks some button i'm showing this panel. Now i wanted to launch this grid in a separate window(should be a child to existing window) and want to make the grid editable, click controls...etc, is it possible?
thanks in advance.
| You should be able to achieve this effect by placing your grid on a separate form, complete with editing stuff. Disable the form and set its parent, (see control.parent), to be the main form panel. When the user wants to edit it, set the grid-form parent to nil and enable it.
Not actually tried this with WinForms, but... |
6,122,867 | 6,122,924 | Handle exception from DLL | I have DLL written in C, which can raise a null-pointer exception. The DLL is used from C++ code. How can I handle this exception from C++ code?
| You can use Structured Exception Handling (SEH). This is the Windows-specific way of catching various exceptions- __try and __except.
|
6,123,212 | 6,192,488 | Are There Any Good C++ Suffix Trie Libraries? | Does anyone know of a really rock solid C++ library for suffix tries? Other than the one in Mummer?
Ideally, I'd like:
Some concept of concurrency.
Good caching behavior.
Permissive license.
Support for arbitrary alphabets.
| Being a bioinformatician, my pick would be SeqAn (check out the sequence index section). It implements a lazy suffix tree and an enhanced suffix array (an equivalent data structure), both of which have good cache behaviour.
|
6,123,226 | 6,123,489 | How to send a file with http with c++ | I want to write a server side code. It should work with popular browsers and wget. My server check that file exists or not, if exists then browser can download it. But I have some problems.
Honestly, I read lots of question-answer (for example: Send binary file in HTTP response using C sockets) but I didn't find out. M... | As to your first question, you should find out the exact size of the file and specify it in your "Content-Length: xxxx\r\n" header. And, of course, you should ensure that the data is sent completely out.
Indeed, in your writeF function you use a std::string as a buffer:
string buffer;
this is not appropriate for binar... |
6,123,327 | 6,129,071 | Use boost::optional together with boost::adaptors::indirected | I am trying to compile the following code:
#include <iostream>
#include <iterator>
#include <vector>
#include <boost/assign/std/vector.hpp>
#include <boost/optional.hpp>
#include <boost/range/adaptor/indirected.hpp>
#include <boost/range/algorithm/copy.hpp>
int main( int argc, char ** argv )
{
using namespace boost... | This is definitely a bug in Boost, but whether that bug is in Boost.Optional or Boost.Iterator is up for debate (I would say the latter, personally).
However, the fix is trivial -- before including any Boost headers, do this:
#include <boost/optional/optional_fwd.hpp>
#include <boost/pointee.hpp>
namespace boost
{
... |
6,123,544 | 6,123,567 | Header should be included once | In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
2.
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
Which is more preferable and why?
| I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.
|
6,123,906 | 6,124,008 | Why a template function receives 2D array with 1D reference when a normal function doesn't | void fun (char (&a)[2]) // 1D reference
{}
template<typename T, int SIZE>
void funT (T (&a)[SIZE]) // 1D reference
{}
int main ()
{
char c[2][2]; // 2D array
fun(c); // error
funT(c); // ok !!!??
}
I can expect that fun() gives error, but how come funT() works fine!
Is there any reference in the standard f... | Because the type of c isn't char [2], it doesn't match the first
function. In the template case, T resolves to char [2], which means
that the final argument type is char (&a)[2][2]. (You can think of it
as the T becoming the equivalent of a typedef to char[2], and
expand the argument type based on that.)
|
6,124,616 | 6,124,716 | Explicit type identifier vs RTTI | is there any advantage of using your own type identifier over RTTI?
e.g.
class A { virtual int mytype() = 0; };
class B : public A { int mytype() {return 1;} };
class C : public A { int mytype() {return 2;} };
Could it be faster? Less overhead? Or should one always use RTTI in such a situation?
| Don't assume that RTTI will have more/less overhead than your solution before testing it.
You should try both solutions and measure the performances to get a reliable answer.
I actually asked myself the same question a few years ago and I ended up adding a member variable to "fasten" the type testing, just like you did... |
6,124,768 | 6,124,891 | how to get local time and put it in a string | I have a method s that has as parameter a date time.
How to write it in c++ ?
In c# it is:
string s(System.DateTime sd);
EDIT!
HOW TO CALL THE S METHOD?! also i would like to have in a string the hour, in another string the second..and so on
Another question is: how to convert the time in a string value that has: day,... | Just an example. google for time.h Below is pseudo code:
#include <time.h>
string getTime ()
{
time_t timeObj;
time(&timeObj);
tm *pTime = gmtime(&timeObj);
char buffer[100];
sprintf(buffer, "%d%d%d", pTime->tm_hour, pTime->tm_min, pTime->tm_sec);
return buffer;
}
|
6,124,903 | 6,124,925 | Identifier not found, even with argument-dependent lookup | I have this function:
short cmd_Draw2DPoly(short ThreeDmode, sds_point startpoint[]){...}
and I call it like this in another class
cmd_Draw2DPoly(0, startpoint);
and this error shows up
error C3861: 'cmd_Draw2DPoly': identifier not found, even with argument-dependent lookup
Does anybody know what is wrong?
| If you call your member function from another class, you need to pass the object on which to call it.
someObject.cmd_Draw2DPoly(0, startpoint);
|
6,125,284 | 6,125,477 | Handle displaying uint8 as an int automatically to an ostream | I have a class with a member of type uint8 and when I try to output it to an ostream it displays as it's char representation. I would prefer it's int representation so I need to static_cast(myStruct.member) each time which is a bit cumbersome and potentially error-prone. Any ideas?
| Implement operator<< on your class and define the cast there. Seems to me like you are violating encapsulation.
|
6,125,425 | 6,125,466 | const for non-reference arguments | If I have this code:
void Foo(aBasicType aIn) //Where aBasicType is int, char etc.
{
//...
}
Is there any point in making it const aBasicType since it is going to be copied anyway? One of the reasons I am asking is because I have seen it in 3rd party code and was wondering if there is something I am not aware of.
| It cannot hurt to declare it const if you know that your function needs not modify its value during execution.
Note that functions that change their arguments, when arguments are passed by value, should be rare.
Declaring your variable const can prevent you from writing if (aIn = someValue).
|
6,125,671 | 6,125,712 | Calculating time length between operations in c++ | The program is a middleware between a database and application. For each database access I most calculate the time length in milliseconds. The example bellow is using TDateTime from Builder library. I must, as far as possible, only use standard c++ libraries.
AnsiString TimeInMilliseconds(TDateTime t) {
Word Hou... | On both Windows and POSIX-compliant systems (Linux, OSX, etc.), you can calculate the time in 1/CLOCKS_PER_SEC (timer ticks) for a call using clock() found in <ctime>. The return value from that call will be the elapsed time since the program started running in milliseconds. Two calls to clock() can then be subtracte... |
6,125,873 | 6,126,006 | Removing const-ness from a type inside template function | void foo (void *p); // library function; can't edit
template<typename T>
void Remove (T *p)
{
// main code
foo(p); // Can we remove const ness of T here ?
}
I have multiple functions like Remove(), it can be called with const T* also, which will not match with foo(void*). Without overloading/specializing Remove()... | If you really need it, there's a boost/C++0x metafunction for that:
template<typename T>
void Remove (T *p)
{
foo( const_cast< typename std::remove_const<T>::type *> (p) );
}
test: https://ideone.com/L6urU
|
6,125,925 | 6,126,188 | Class destructor c++ | I've got a question about destructors in c++.
I've got a class like this :
class X {
private:
string m_instanceName
string m_path;
ConnexionHashMap m_connexions;
Module** m_moduleType;
Powerdomain* m_powerDomain;
Module ** m_father;
};
Here are some information concerning ConnexionHashMa... |
If I don't want to delete the m_modulType the m_powerDomain and m_father (because they are likely to be referred to by another object, do I have to explicitely write a destructor method?
m_powerDomain, m_father, and m_modulType are pointers and the objects they point to will not be deleted unless you do so explicitly... |
6,125,926 | 6,126,177 | kill -3 for C++ application on solaris | I have an application written with C++ and running on Solaris. The application does lots of things and sends a heartbeat to a watchdog application for saying "I am alive". If something goes wrong the application does nothing (also does not send heartbeat). In a Java app, kill -3 helps me to see what is going on. Should... | Both Solaris and Linux support the gcore command to create a core dump of a running process. Then you can use gdb (or dbx) to analyze the core file.
|
6,126,042 | 6,126,101 | Compile several files together? | I have
Data.cpp
Data.h
User.cpp
User.h
main.cpp
Main.cpp need data.cpp and user.cpp. How do I link or compile them? They all in same directory? (please be more specific, like which file to compile first.)
My system is: Mac OS X, g++ compiler in terminal.
| The simplest way :
g++ Data.cpp User.cpp main.cpp
More advanced way : use a makefile
|
6,126,065 | 6,126,392 | Qt what headers to include? | While programming in C++ with Qt what includes should I make? Just 2 includes
#include <QtCore>
#include <QtGui>
or
#include <QWidget>
#include <QDialog>
#include <QList>
#include <QKeyEvent>
#include <QObject>
for every class?
Thanks!
| Include only the definitions of the classes you need - anything else isn't just lazy, it's extremely wasteful and to my mind bad style.
Including QtGui (which itself includes QtCore) will lead to adding about 350(!) header files to your compilation, when in your example you only needed 6. Compiling will take longer, an... |
6,126,109 | 6,132,325 | JNI: Overhead of holding Java object references within the native code? | I am looking into integrating a JRE into a C++ application via JNI.
What is the overhead of holding a large number of references to Java objects within the C++ application (global references in JNI parlance)?
Are there any problems I should be aware of with this approach (other than the obvious, such as manually deal... | (a) the overhead is the same as if you were doing it from Java. You are preventing the objects from being garbage-collected.
(b) Holding object references across JNI calls can be fatal to the JVM unless you do it correctly. You need to read carefully the section on Global and Local References in the JNI specification. ... |
6,126,133 | 6,174,322 | boost deserialization problem of juce::String with XML wide archive | I'm using boost::serialize to serialize a document wherein I use f.i. a juce::String. Like so:
template<class Archive>
void serialize( Archive & ar, const unsigned int version )
{
ar & boost::serialization::make_nvp("title", m_docTitle);
...
}
For boost::serialize to accept juce::String as a primitive type I d... | Finally I got it to work (for XML archive nota bene), by using boost basic_xml_grammar to parse the string in operator>> , like so:
typedef boost::archive::basic_xml_grammar<wchar_t> xml_wgrammar;
template <class IStream>
IStream& operator>> (IStream& stream, JuceString& s)
{
std::wstring t;
xml_wgrammar gramm... |
6,126,227 | 6,126,367 | Templating throws out a lot of errors | I am creating a helper namespace for one of my projects, i wanted it to be able to use all types like ints, floats, doubles etc. But it seems like i just cant get the templating right.
Anyways, here is my current code, my compiler doesn't spit out errors about the file itself, though when i compile it it spits out hund... | Your deg/rad conversion functions won't work right if you pass in an int for T because PI will get truncated to int before doing the conversion. I can't quite make out why you have that in there.
Using variable names like min and max will cause problems if you have a using namespace anywhere.
Your abs function is missi... |
6,126,443 | 6,126,696 | Programmatically restart a Windows Service | I know this can be done in C#/.Net but I was wondering whether it can be done calling the Windows API?
I have a service which will service DHCP requests, when I want to update the configuration for the service I need to stop the service, rewrite its INI file and then start the service again.
Any help appreciated!
|
Open the service control manager with OpenSCManager.
Open the service you want to control with OpenService.
Use ControlService or ControlServiceEx with a SERVICE_CONTROL_STOP parameter to stop the service.
Do whatever you need to do.
Use StartService to restart the service.
Use CloseServiceHandle to close the service ... |
6,126,450 | 6,126,521 | Can a derived class in the CLR intercept / cloak a parent's class's methods, while still keeping intellisense? | Is it possible for the CLR to create Object X that inherits from Object Y where
Object Y is of type Object
All methods of Y are available to object X.
Callers of Object X think they see all of Y's objects
Object X masks the methods above and does some 'work' prior to running each method
That 'work' may include coun... | Yes. This is called proxying an object. Castle DynamicProxy is designed for doing exactly this. Krzysztof Koźmic has produced an excellent tutorial about it.
It works by creating an object (X in your scenario) at runtime which inherits from the object you want to proxy (object Y). You provided an object which implement... |
6,126,593 | 6,126,960 | Boost unordered_map - bug or improper usage? | I am getting strange behavior from within the boost::unordered_map library (v1.45.0).
In my class I create an object:
boost::unordered_map<uint16, MyStruct *> bufferStructMap;
Then I initialize it in the constructor initialization list:
MyClass::MyClass () : bufferStructMap( ) { .... }
Then I try to pull something ... | Mark B is probably right. If not, it looks like a bug in Boost.
Although... Since std::tr1::unordered_map (and the C++0x version? not sure) does not provide at(), you might want to just use find().
// Save typing, allow easy change to std::unordered_map someday
typedef boost::unordered_map<uint16, MyStruct *> map_t;
... |
6,126,635 | 6,126,825 | break long string into multiple c++ | I have a string that is received from third party. This string is actually the text from a text file and it may contain UNIX LF or Windows CRLF for line termination. How can I break this into multiple strings ignoring blank lines? I was planning to do the following, but am not sure if there is a better way. All I need ... | I'd use getline to create new strings based on \n, and then manipulate the line endings.
string textLine;
vector<string> tokens;
istringstream sTextLine;
string line;
while(getline(sTextLine, line)) {
if(line.empty()) continue;
if(line[line.size()-1] == '\r') line.resize(line.size()-1);
if(line.empty()) continue... |
6,126,709 | 6,126,831 | Read data from a disk in c++ | I'm trying to read some data that lies outside of the partition table, I can successfully read the raw data, but it appears to be encoded in Unicode (UTF-8) or something. There is an application that has been written to read this data and display it properly so I know it can be done.
This data is called "Image Safe Dat... | When you print it you're interpreting the data as a char. Some of the values are in the a-zA-Z "normal, printable" range and so print as you'd expect. Others, like '0' are special and unprintable directly. You probably want to print the bytes as hex, not characters. To do that:
std::cout << std::hex << std::setw(2) << ... |
6,126,833 | 6,126,921 | GetLogicalDriveStrings, why list of strings | Do I understand correctly that this function returns drive letters?
If yes, then why does GetLogicalDriveStrings gives series of null-terminated strings and not series of chars?
| Because it returns strings that can be used as input to functions like GetDriveType which require the input to be in the form "c:" not just 'c'.
|
6,126,980 | 6,127,080 | Get pointer to IMAGE_DOS_HEADER with GetModuleHandle? | I am trying to get the image base of my process once it is loaded in memory. From my understanding, you can call GetModuleHandle to get the image base. My question is, does the handle returned essentially point to the IMAGE_DOS_HEADER struct such that you could do the following:
PIMAGE_DOS_HEADER DosHeader;
DosHeader =... | This is correct, though if you want the module handle of of a dll you need to specify its path. Otherwise you will get the handle to the process exe. You should also check the returned HMODULE first to see that its valid.
An example of how to get the virtual size of the module:
std::size_t GetModuleSize(const char* szM... |
6,127,115 | 6,445,473 | Executing a user-mode executable from kernel-mode | I'm building a HW-simulator for our driver team. Now, the simulator is devided in to 2 modules:
First module runs inside the driver, in kernel mode and that's where the main interface between the driver and the HW-Simulator.
Second module is an executable user-mode code which generates data for the simulator and trans... | There isn't a clean way to do this in the Windows kernel. The user-mode API CreateProcess to create processes use undocumented APIs (NtCreateProcess/NtCreateThread) to create a process.
The recommended thing to do would be to have a "partner service", a user-mode service that communicates with your driver using IOCTL. ... |
6,127,187 | 6,127,460 | a reference of type "std::string&" (not const-qualified) cannot be initialized | When I try to compile the following function I get the error.
string& foo(){
return "Hello World";
}
Error:
1 IntelliSense: a reference of type "std::string &" (not const-qualified) cannot be initialized with a value of type "const char [12]"
| There are two problems with your code. First, "Hello World!" is a
char const[13], not an std::string. So the compiler has to
(implicitly) convert it to an std::string. The result of a
conversion is a temporary (rvalue in C++-speak), and you cannot
initialize a reference to a non-const with a temporary. The second i... |
6,127,206 | 6,127,442 | Utility class for temporary error information storage? | I have been writing a light-weight framework to wrap the Windows API for personal projects and some fun. What I think is a good design method is that each class in the framework manages its own error information whenever something goes wrong. I have a simple error class like so:
class Error
{
public:
struct ErrorD... | Have you considered using exceptions and throwing your ErrorData class instead? That seems better than either inheritance or composition.
It almost looks like getSystemError should be a namespace free-function instead of a member (it looks like everything it needs is passed into its parameters).
|
6,127,357 | 6,132,843 | Building Qt Creator projects from command line | I'm in the process of writing a build script to automate build and release tasks. I have a Qt Creator project which has three configurations, two of which I want to completely rebuild from scratch without any precompiled headers and existing .o files to skip (release and release_production). The latter is the same exc... | There are two steps involved here:
Running qmake to generate Makefiles. The usual command is
c:\qt\4.7.2\bin\qmake.exe" path\to\some\project.pro -r -spec win32-g++ CONFIG+=...
The -spec switch is important. Make sure you supply a valid makespec file. CONFIG needs to be specified in this step.
Running make to compile ... |
6,128,211 | 6,128,306 | Releasing virtual memory reserved by C++ 'new' on Windows | I'm writing a 32-bit .NET program with a 2 stage input process:
It uses native C++ via C++/CLI to parse an indefinite number files into corresponding SQLite databases (all with the same schema). The allocations by C++ 'new' will typically consume up to 1GB of the virtual address space (out of 2GB available; I'm aware ... | This is not something you can control effectively from the C++ level of abstraction (in other words you cannot know for sure if memory that your program released to the C++ runtime is going to be released to the OS or not). Using special allocation policies and non-standard extensions to try to handle the issue is prob... |
6,128,214 | 6,129,712 | how to determine whether a dll has been registered with my c++ function? | A newbie question-
I want to write a wrapper function in windows c++ which will look into some input parameters passed and based on whether an associated dll is registered or not would respond to the application.
So basically i need to
1)register dlls with my wrapper fn
2)the wrapper should scan through the registered ... | I'm not sure what you mean by register - are we talking about COM registration or your own custom registration system?
In any case, once you know what DLLs to load, use LoadLibrary to load the DLL into memory, and GetProcAddress to get pointers to exported functions from the DLL. If you're doing a plugin-style thing, y... |
6,128,344 | 6,128,463 | Function pointer pointing to a function that takes a function pointer | How do I declare a function pointer that points to a function taking the same function pointer as the argument?
I've tried the following without success:
typedef void (*fnptr)(void (*)());
void func(fnptr)
{
/* ... */
}
void func2(fnptr)
{
/* ... */
}
void main()
{
fnptr fn = &func;
func2(fn);
}
Is ... | I very much doubt it, but you can get the needed recursion by introducing a struct.
struct Rec;
typedef void (*RecFun)(const Rec&);
struct Rec {
RecFun fun;
};
Example of use:
#include <iostream>
void nothing(const Rec& rec) {}
Rec recNothing = { nothing };
void f(const Rec& rec)
{
std::cout << "f\n";
... |
6,128,655 | 6,128,711 | problem in #defining cout? | A friend of mine told me that this code has some problems:
#include <iostream>
#include <cstdio>
using namespace std;
#define cout printf
int main(){
cout("cout");
}
He didn't give me the reason and asked me to figure it out which I couldn't. The code seems to be working fine, what could possibly be wrong with ... | As far as I know the Standard forbids defining names (with #define) declared in any standard library header.
Found this in n3290 ($17.6.4.3.1)
17.6.4.3.1 Macro names [macro.names]
1 A translation unit that includes a standard library header shall not ... |
6,129,029 | 6,129,107 | Type of CLOCKS_PER_SEC | What datatype is CLOCKS_PER_SEC typically represented as? long unsigned int? clock_t? Does it vary from implementation to implementation?
I ask because I use CLOCKS_PER_SEC in a return value, and I want to make sure I use the most appropriate type.
| All that the C standard promises is that CLOCKS_PER_SEC is a constant expression with the type clock_t which must be an arithmetic type (could be an integer or a floating type).
(C99 7.23 Date and time <time.h>)
I think that clock_t is typically a long, but I wouldn't bet my life that I'm right.
My usually trusty Harbi... |
6,129,165 | 6,129,978 | JNA loading libraries | I've got two libraries, one with Ada objects and one with C++ objects (I don't have a lot of control about which goes where)
The Ada stuff references the C stuff and vice versa...
This symbol is in libIPCAda.so: ipc_manager_shutdown_c
This symbol is in libIPCC.so: stream_buffer_header_size
When I do these JNA Calls:
... |
The cross-link is going to happen in native-code-land, not inside Java. As far as JNA knows, it's loading two completely independent native libraries.
You need to supply the libraries themselves with each others' locations. There are a couple ways to do this; either set the rpath when compiling the shared library, o... |
6,129,260 | 6,129,290 | Please suggest something better than gotoxy function in C++ | I have written a program that consists of multiples and multiples of function each of which are printing several things on the console when control is passed to them. Now I am trying to print everything in the center of the screen rather than on the upper left corner of the screen. For that purpose, the only thing I kn... | Write a small helper function (e.g. printCentered(std::string) ) that receives the string to be printed. This function moves the cursor to the center and then prints the parameter. Then replace your couts with a call to this function.
|
6,129,314 | 6,129,361 | How do I pass multi-dimensional arrays of unknown size into a function using pointers in c++? | Like the question says, I am trying to pass multi-dimensional arrays into a function to print it to a file for an engineering project. The format for which the data is inputted CANNOT be changed, so please don't suggest I just input it as a different datatype.
This particular function anticipates a two-dimensional arra... | You can't. Multidimensional arrays are syntactic sugar, and are compiled directly into the code that does manipulations on the array, which is a single memory block. The dimensions are not passed into the function as parameters or anything like that as part of the array, as things are done in e.g. Java or C#.
If you ne... |
6,129,348 | 6,129,422 | C++ Vector Loop and push_back problem? | I could not figure out what went wrong when I tried to modify vector array.
Here is my vector array:
14248 DL AAAAA
14248 DL AAAAA
14248 DL AAAAA
14248 DL AAAAA
14248
14248
14248
14248
What I want to try to do here is, if vector string contains "AAAAA" I will push back as "-" to different vector cRntiModDash. If NOT ... | vector<std::string> cRntiModDash;
// ...
all.push_back(&cRntiModDash);
You store a pointer to the (presumably) local variable cRntiModDash in all. As soon as cRntiModDash goes out of scope, all will contain a pointer to a not longer valid object. That memory location will be reused by other variable... |
6,129,383 | 6,129,485 | High Perfomance: Do call C++ methods directly from a python backend? | My Python backend (Django) has to request to a C++ library to get a result (with help of ctypes module).
Is it normal to call a C++ method directly? Or may be I need an intermediate thread manager that starts a new thread when python script wants a result?
| Basically you have to decide what kind of operation flow you want. If you prefer synchronous processing you can call you method directly, if you favor asynchronous processing you will need an intermediate solution.
However, you have to be aware, that when you call the C++ routine directly form your Django app the call ... |
6,129,822 | 6,219,749 | virtual joystick driver (VJoyD) and Direct Input | I have couple of questions:
What is exactly VJoyD used for? Based on my reading win WDK (Windows Driver Kit) it provides joystick services in Windows (http://msdn.microsoft.com/en-us/library/ff542258(v=vs.85).aspx). If that is the case, can I use it to send commands from my hardware to Vjoyd so my hardware can look li... | Answering my own questions for the benefit of others:
1.A: VJoyD used by old version of OS to handle joystick input, dead by now.
2.A: In the past, you there were some alternatives but now replaced by HID class.
|
6,129,933 | 6,129,979 | Call an External C++ function and Memory Leaks: is all allocated memory cleaned up after finishing Python script? | Python script calls an external C++ function (using ctypes). Memory leaks are possible when execution the C++ function.
Will all allocated memory (in C++ function) be automatically cleaned up after finishing of the Python script?
| Yes, It will all be returned to the OS once the python interpreter exits. This is true for all processes - nothing specific to python or c++.
|
6,130,100 | 6,130,497 | Using volatile to prevent compiler optimization in benchmarking code? | I am creating a little program measure the performance difference between containers of types boost::shared_ptr and boost::intrusive_ptr. In order to prevent the compiler from optimizing away the copy I declare the variable as volatile. The loop looks like this:
// TestCopy measures the time required to create n copies... | The C++03 standard says that reads and writes to volatile data is observable behavior (C++ 2003, 1.9 [intro.execution] / 6). I believe this guarantees that assignment to volatile data cannot be optimized away. Another kind of observable behavior is calls to I/O functions.
The C++11 standard is even more unambiguous in ... |
6,130,595 | 6,130,607 | What makes something an Abstract Class in C++ |
Possible Duplicate:
What is the difference between a concrete class and an abstract class?
I was coding something in Visual C++ 2008 doing an exercise in a book I am reading when I held my cursor over one of the classes and it told me it was an abstract class. Now I know it is an abstract class as that is what this... |
Is the pure virtual a dead giveaway
In C++, yes. Since it has no abstract keyword or equivalent, the common idiom to make a class abstract is to declare a pure virtual function in it (which prevents instantiation).*
For this same reason, in C++ there is not much difference between an interface and an abstract class -... |
6,130,823 | 6,130,969 | pthreads: perform function on main thread | I'm looking for the analogous of Cocoa's
-[NSObject performSelectorOnMainThread: withObject: waitUntilDone:]
method.
So basically I have a function that does some work on a separate thread but it must perform some synchronous calls that need to be performed on the main one.
| in cocoa, the message is added to the run loop, which is cleared as part of its iteration.
to simulate this:
you'll a want a run loop
an abstract message system
and a reference counting mechanism (in most cases)
a way to add those messages to a run loop for scheduled execution
timers would be a nice addition
to accom... |
6,130,924 | 6,131,532 | How to write SFINAE to test for parser rule? | I have a sfinae class that tests whether a class is a parser rule (AXE parser generator library).
The axe::is_rule<P>::value should evaluate to true iff P satisfies parser rule requirements. A parser rule must have one of the following member functions, taking a pair of iterators and returning axe::result<Iterator>:
te... | I think the API of is_rule is not sufficient. For example unfortunate is a rule only if used with iterators of type const unsigned char*. If you use unfortunate with const char*, then it doesn't work, and is thus not a rule, right?
That being said, if you change the API to:
template <class R, class It> struct is_rule... |
6,131,009 | 6,131,460 | interleave 2 linked list C++ | I have the solution code here:
// Pre-condition: The fronts of two linked lists are provided.
// Post-condition: A linked list is returned that is the result of
// interleaving the elements from each provided list.
// (e.g. {1, 2, 3} & { 4, 5, 6} would return {1, 4, 2, 5, 3, 6}
Node* interleave( Node*& front1, Node*&... | There are a few mistakes in your code:
Node* interleave( Node*& front1, Node*& front2 )
I don't see the need for a reference to a pointer, since the first item in front1 will keep on being the first, and you don't need to mess with front2 at all.
Node* newNode = new Node;
while(front1!=NULL && front2!=NULL){
newNo... |
6,131,123 | 6,131,231 | Generating hardware based computerID | I had a question regarding generating a specific computer ID for licensing purposes. Preferably this ID should be hardware based, and thus should not change if the user reformats for example. Also it should not be easy (or preferably even impossible) for the user to change the information that the ID is generated from.... | You can use the first MAC address, which is assigned by the manufacturer of the hardware and will never change.
Something like this:
/**
return string containing first MAC address on computer
requires adding Iphlpapi.lib to project
*/
string GetMac()
{
char data[4096];
ZeroMemory( data, 4096 );
unsi... |
6,131,247 | 6,131,299 | Alphabetizing (Sorting) Vector of Pointers | I have a vector of pointers which point to a set of Critic objects. Each Critic has attributes such as UserID, First Name, Last Name, etc.
I mocked up an modified quickSort in order to sort the vector of pointers by the First Name of each Critic. The function works as intended, but only for the first few instances in t... | If its not a homework, then why don't you use std::sort providing a comparer as third argument?
bool compare_func(const Critic* c1,const Critic* c2) { /***implement it***/ }
vector<Critic*> v;
//...
std::sort(v.begin(), v.end(), compare_func);
|
6,131,307 | 6,131,404 | ifstream vs. fread for binary files | Which is faster? ifstream or fread.
Which should I use to read binary files?
fread() puts the whole file into the memory.
So after fread, accessing the buffer it creates is fast.
Does ifstream::open() puts the whole file into the memory?
or does it access the hard disk every time we run ifstream::read()?
So... does i... | Are you really sure about fread putting the whole file into memory? File access can be buffered, but I doubt that you really get the whole file put into memory. I think ifstream::read just uses fread under the hood in a more C++ conformant way (and is therefore the standard way of reading binary information from a file... |
6,131,687 | 6,132,566 | QGraphicsView not repainting on scroll event | QT 4.7
I have a QGraphicsView / QGraphicsScene. The scene has a custom QGraphicsItem the whole scene is not displayed at one time, so it has a viewport.
I'm overriding the paint() method of my QGraphicsItem as follows:
void paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *... | A guess:
The QPainter that comes to your paint method already has a transform on it that takes into account the viewport attributes (scale, rotation, etc.). When you call setTransform within your paint method you are blowing all that away. You probably want to perform a matrix operation on the existing transform rather... |
6,131,700 | 6,131,914 | Implementing double dispatch with two class hierarchies in C++ | I want to create an event dispatch system with a (shallow) hierarchy of Events that can be observed by a (shallow) hierarchy of EventObservers. I figured double-dispatch would allow a wide variety of both Events and EventObservers without having to have a function for every single combination.
I have code like this:
cl... | Either your base observer class needs to know how to observe any event type, or your base event class needs to know how to be observed by any observer type. Otherwise your double dispatch simply loses the type information gained from your initial dispatch.
In your case, if you added virtual void observe( EventA* evt )... |
6,131,704 | 6,131,757 | c++ virtual function reimplementation | even i think that question is stupid. but i've a little experience.
i have a base class that has such method:
class A{ virtual void func(int)=0 };
and inherited class
class B :public A
{
//how should i write?
//a
virtual void func() { implementation...}
//b
void func() {imp... | You ask, "what if i don't want that the function that was virtual in ansestor, will be virtual in subclass?"
Sorry, but every function that is declared virtual in a base class, is also virtual in all derived classes.
It actually doesn't matter whether you use the virtual keyword in the derived-class declaration. Optio... |
6,131,721 | 6,131,793 | cannot convert parameter 1 from 'char *' to 'uint8_t *' | void OnReceived(std::shared_ptr<uint8_t> buffer, int len) {
.........
}
int main(){
std::vector<char> buffer(1000);
OnReceived((std::shared_ptr<uint8_t>)buffer.data(),rcvlen);
}
am trying to cast it but i cant i dont know why!!!
Error 1 error C2664: 'std::tr1::_Ptr_base<_Ty>::_Reset0' : cannot convert parameter 1... | You really don't want to do that. Aside from the fact that char and uint8_t may be distinct types, even if you force the code to compile, your buffer will be deallocated twice, likely crashing your program. Just change OnReceived to accept a raw pointer.
|
6,132,129 | 6,132,186 | How to deal with spaces within paths when using the system()? | I am still new to C++ and am working out a way to open a program within my C++ program.
The problem is that whenever I have spaces in my paths, it sees it as different parameters.
int _tmain(int argc, _TCHAR* argv[])
{
system("C:\\Users\\blah\\Desktop\\a\\ b.txt");
return 0;
}
The output I receive is:
'C:\User... | You can double quote your string literal. Edit: Also just noticed that your backslashes were not escaped so updated below :P
system("\"C:\\Users\\blah\\Desktop\\a\\ b.txt\"");
Also let it be known for the record that you really shouldn't use system. Try fork, spawn, or perhaps even the unofficial boost.process class ... |
6,132,204 | 6,132,552 | No suitable constructor exists to convert from "dumb pointer" to "smart pointer" | struct A
{
A(int a);
};
struct B
{
B();
void b(std::shared_ptr<A> a);
};
int main()
{
A a(1);
B b;
b.b(&a);
}
So I got this error, sorry guys it's my frist time with the smart pointers!!
Error:
no suitable constructor exists to convert from "A *" to "std::tr1::shared_ptr<A>"
How do I fix th... | Others already ranted on the design error of your code, but not the real problem why the code doesn't even compile. shared_ptr has a constructor that accepts a raw pointer, but it is marked as explicit, which means you have to explicitly write out that you want to construct a shared_ptr instance. What your function cal... |
6,132,235 | 6,132,266 | What is wrong with this template code? | #include <iostream>
#include <map>
#include <vector>
template<typename T>
class foo {
public:
foo(T val) : m_Value(val) { };
T get_value() const { return m_Value; };
void set_value(const T& t) { m_Value=t; };
bool operator<(const foo<T>& x) { return x.get_value() < m_Value; };
... | print_first is a const method. Therefore the member m_Map is also const, and its begin method doesn't return an ordinary iterator, but a const_iterator. Change
typename std::map<foo<T>,std::vector<foo<T> > >::iterator it;
to
typename std::map<foo<T>,std::vector<foo<T> > >::const_iterator it;
and you should be good... |
6,132,241 | 6,133,573 | Can I create a ActiveX Control from a WPF UserControl and use in a non CLI C++ application? | I have created a Windows Forms UserControl that can be exposed as an ActiveX Control. Now I am trying to do the same with a WPF UserControl. The Winforms UserControl base class I noticed is ComVisible however the WPF UserControl class is not. Am I trying to do the impossible?
Is the only way to achieve this to write a ... | Yes, I think ElementHost is the approach you will need to use if there is a chance of this working.
This is because WPF controls are inherently windowless with everything being rendered in retained mode via a DirectX surface which WPF maanges.
There are interfaces for "windowless" ActiveX controls but the COM interop... |
6,132,259 | 6,132,554 | When comparing Windows, console, static libraries and DLL's in C++, what are the latter two used for? | I'm having difficult understanding my text, and I want to know each section extremely well. Please, be as descriptive as possible. Thank you, very much.
| Programmers often find they have some code they would like to use in several programs, or code they would like to allow other programmers to make use of. They could copy-and-paste the logic into every program, or they could place the logic in common header and implementation files that they include in every project. ... |
6,132,385 | 6,132,528 | A good performance alternative to PHP - String/File Manipulation | I have a project that is done but needs better performance.
The gist of the project is that I'm taking XML and converting it to CSV files. The files represent data to be loaded into a Database.
Right now I'm using PHP to unzip the zip file that contains the XML. Then I parse, convert to CSV, and rezip.
It's been fine... | You should give Perl a try if PHP doesn't deliver what you wont, but I doubt, maybe you are doing something wrong there (logically).
What kind of XML parser are you using? (Its better be a SAX one...).
Also, it would be nice to see some code (how you parse the XMLs...)
|
6,132,510 | 6,132,905 | When can I release a source PBO? | I'm using PBOs to asynchronously move data between my cpu and gpu.
When moving from the GPU i know I can delete the source texture after I have called glMapBuffer on the PBO.
However, what about the other way around? When do I know that the transfer from the PBO to the texture (glTexSubImage2D(..., NULL)) is done and I... | I think after calling glTexImage you are safe in deleting or reusing the buffer without errors, as the driver handles everything for you, including deferred destruction (that's the advantage of buffer objects). But this means, that calls to glMapBuffer may block until the preceding glTexImage copy has completed. If you... |
6,132,635 | 6,132,841 | How to listen for browser requests with POCO and c++ | I would like to know what Poco classes to use in listening for a browser request. This is for a proxy server.
In general I want to open a port and wait for a request from a browser.
Please give an example as I'm quite new to Poco and C++ in general.
| You can look at the HTTPTimeServer (http://pocoproject.org/docs/00100-GuidedTour.html#4) example. Basically you need:
Poco::Util::ServerApplication. You derive from this class to host
the server process.
Poco::Net::ServerSocket to handle the
socket to listen at.
Poco::Net::HTTPServer which is in
charge of accepting co... |
6,132,720 | 6,132,851 | Finding rotation between two congruent triangles | I'm working on a 3D mesh parsing tool. Currently, I'm trying to determine the rotation between two congruent triangles in 3D space—we'll call them ABC and DEF.
I'm able to translate points A and D to the same location and now need to determine a rotation that would place DEF on the same plane and in the same orientati... | Your right with your first part rotating AB onto DE (or the other way). But this only aligns one edge. To align the other two, you still need to rotate C onto F (after your first rotation). The neccessary angle and axis can be computed by just rotating the two face normals of the triangles onto each other using your pr... |
6,132,753 | 6,132,765 | Automatically change between std::string and std::wstring according to unicode setting in MSVC++? | I'm writing a DLL and want to be able to switch between the unicode and multibyte setting in MSVC++2010. For example, I use _T("string") and LPCTSTR and WIN32_FIND_DATA instead of the -W and -A versions and so on.
Now I want to have std::strings which change between std::string and std::wstring according to the unicod... | Why not do like the Win32 API does: Use wide characters internally, and provide a character-converting facade of DoSomethingA functions which simply convert their input to Unicode.
That said, you could define a tstring type like so:
#ifdef _UNICODE
typedef std::wstring tstring;
#else
typedef std::string tstring;
#endif... |
6,133,080 | 6,133,119 | What's the proper way to share an enum across multiple files? | I would like to use the same enum in both the client and server parts of my current (C++) project, but am unsure of the proper way to do this. I could easily just write the enum in it's own file and include that in both files, but that feels like it's poor practice. Would putting it in a namespace and then including ... | Putting it in a header file seems reasonable, and wrapping it in a namespace can be useful too. Something i find myself doing with enums is
contents of whatevsenum.hpp:
namespace whatevs
{
enum Enum
{
FOO = 0,
BAR,
BLARGH,
MEH,
SIZE
};
} // namespace whatevs
and then... |
6,133,322 | 6,133,720 | What does a branchless if in C++ look like? | I realize I've got a great lack of knowledge in that area (fancy way of saying I don't know jack about it).
Is there some documentation as to how and when to use them?
| Apart from all the twiddling based branchless code (which won't cover everything, such as FP), you get instructions specifically meant for branchless code creation, these would be SETcc, FCMOVcc and CMOVcc under x86, which perform operations based on the condition flags from a comparison.
a really simple example would ... |
6,133,458 | 6,133,479 | IRC protocol message formatting | I've been searching for a while, but I can't seem to find the message formatting of the IRC protocol. For example, if I wanted to enter a channel, the client might send "enter channelname nick" or something along those lines. Does anyone know?
| Look at the RFC: http://www.irchelp.org/irchelp/rfc/rfc.html
Or open your favorite IRC client and use a sniffer to see what the incoming/outgoing packets look like.
I'm guessing you are asking how to join a channel:
http://www.irchelp.org/irchelp/rfc/chapter4.html#c4_2_1
You simply send: JOIN #channel\r\n
|
6,133,647 | 6,133,665 | How do I list subdirectories in Windows using C++? | how do I list subdirectories in windows using C++? Using code that would run cross-platorm is better.
| http://msdn.microsoft.com/en-us/library/aa364418(v=vs.85).aspx
and
http://msdn.microsoft.com/en-us/library/aa365200(v=vs.85).aspx
its crossplatform between windows vista/7 or maybe xp :P
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.