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 |
|---|---|---|---|---|
2,810,232 | 2,810,738 | Unwanted debug session | Try this code I created,when I use it in Borland C++ and try the remove-function a debug session opens up and it points to a file called "xstring",and it is saying "EAccessViolation".
it points to this line in the file:
return (compare(0, _Mysize, _Right._Myptr(), _Right.size()));
//---------------------------------------------------------------------------
#include<iostream>
#include<string>
#include<fstream>
#include<list>
#pragma hdrstop
using namespace std;
struct Mail{
string name;
string ammount;
};
//---------------------------Call_Functions-----------------------------
void new_mail(list<Mail>& l);
void show_mail(list<Mail> l);
void remove(list<Mail>& l);
//---------------------------------Menu--------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
list<Mail> mail;
bool contin = true;
char answ;
do{
cout<<'\n'<<'\t'<<'\t'<<"Menu"<<endl
<<'\t'<<'\t'<<"----"<<endl
<<"1. New mail"<<endl
<<"2. Show mail"<<endl
<<"3. Remove mail"<<endl
<<"4. Exit"<<endl<<endl;
cin>>answ;
cin.ignore(1000, '\n');
switch (answ) {
case '1':
new_mail(mail);
break;
case '2':
show_mail(mail);
break;
case '3':
remove(mail);
break;
case '4':
exit(1);
default:
cout<<"Choice not recognized";
}
}
while(contin);
return 0;
}
//------------------------------Functions-------------------------------------
//------------------------------New_mail--------------------------------------
void new_mail(list<Mail>& l){
Mail p;
cout<<endl<<"Type in the name of the new mail ";
getline(cin, p.name);
cout<<"Now type in the cost: ";
getline(cin, p.ammount);
l.push_back(p);
}
//------------------------------Show_Mail-------------------------------------
void show_mail(list<Mail> l){
list<Mail>::iterator it;
cout<<"\nAll mail:\n\n";
for (it = l.begin(); it != l.end(); it++) {
cout<<(*it).name<<'\t'<<'\t'<<(*it).ammount<<endl;
}
}
//------------------------------Remove----------------------------------------
void remove(list<Mail>& l){
list<Mail>::iterator it;
string name;
cout<<endl<<"What is the name of the mail you want to remove?: ";
getline(cin, name);
for (it = l.begin(); it != l.end(); it++) {
if ((*it).name == name) {
l.erase(it);
}
}
}
//------------------------------End-----------------------------------------
Why does it show this error,and how can I solve it?
| do a break; after l.erase(it);
iterator becomes invalid you incremante it by it++ check against it != l.end() succeds
(*it).name is used for comparison but is invalid and causes exception
|
2,810,280 | 2,810,339 | How to store a 64 bit integer in two 32 bit integers and convert back again | I'm pretty sure its just a matter of some bitwise operations, I'm just not entirely sure of exactly what I should be doing, and all searches return back "64 bit vs 32 bit".
| Use a union and get rid of the bit-operations:
<stdint.h> // for int32_t, int64_t
union {
int64_t big;
struct {
int32_t x;
int32_t y;
};
};
assert(&y == &x + sizeof(x));
simple as that. big consists of both x and y.
|
2,810,297 | 2,810,409 | How to handle server-client requests | Currently I'm working on a Server-Client system which will be the backbone of my application.
I have to find the best way to send requests and handle them on the server-side.
The server-side should be able to handle requests like this one:
getPortfolio -i 2 -d all
In an old project I decided to send such a request as string and the server application had to look up the first part of the string ("getPortfolio"). Afterwards the server application had to find the correct method in a map which linked the methods with the the first part of the string ("getPortfolio"). The second part ("-i 2 -d all") got passed as parameter and the method itself had to handle this string/parameter.
I doubt that this is the best solution in order to handle many different requests.
Rgds
Layne
| To me it seems you're having two different questions.
For the socket part, I suggest you use Beej's guide to socket programming if you want to have full control about what you do. If you don't want to/don't have the time to treat this part yourself, you can just use a C++ socket library as well. There are plenty of them; I only used this one so far, but others might be as just good (or even better).
Regarding your parsing algorithm, you may first write down everything about the message format, so you'll have a strict guideline to follow. Then process step by step:
First, extract the "first word" and just keep the following parameters in some list. Check if the first word is valid and if it is known. If the "first word" does not match with any of the predefined existing functions, just ignore the message (and eventually report the error to the client application).
Once you have the matching function, simply call it passing the others parameters.
This way, each function will do a specific task and your code will be splitted in an elegant way.
Unfortunately, it is difficult for me to be any more explicit since we somehow lack of details here.
|
2,810,530 | 2,810,561 | hiding inner class implementation using namespace | I am developing a library and a would like to provide my users a public interface separate from the real implementation that is hidden in a namespace. This way, I could change only the class HiddenQueue without changing myQueue that will be exposed to users only.
If I put the C++ code of HiddenQueue in the myQueue.cpp file the compiler complains saying _innerQueue has incomplete type. I thought that the linker was able to resolve this. What I am doing wrong here?
// myQueue.h
namespace inner{
class HiddenQueue;
};
class myQueue{
public:
myQueue();
);
private:
inner::HiddenQueue _innerQueue;
};
///////////////////////////
// myQueue.cpp
namespace inner{
class HiddenQueue{};
};
| The compiler needs to know the exact memory layout of an object by looking at the header file it's defined in.
Your code says that class MyQueue has a member of type InnerQueue, which will be part of the memory layout of MyQueue objects. Therefore, to deduce the memory layout of MyQueue it needs to know the memory layout of InnerQueue. Which it does not, because you say "oh well, it's defined elsewhere".
What you are trying to do is closely related to "the PIMPL idiom"/"compiler firewall" technique.
To solve the problem, you must either include HiddenQueue.h in your header or declare _innerqueue as a pointer:
class myQueue {
public:
myQueue();
private:
inner::HiddenQueue* _pinnerQueue;
};
Using a pointer is possible because a pointer has a known memory size (dependent on your target architecture), therefore the compiler doesn't need to see the full declaration of HiddenQueue.
|
2,810,887 | 2,810,924 | Win32 Event vs Semaphore | Basically I need a replacement for Condition Variable and SleepConditionVariableCS because it only support Vista and UP. (For C++)
Some suggested to use Semaphore, I also found CreateEvent.
Basically, I need to have on thread waiting on WaitForSingleObject, until something one or more others thread tell me there is something to do.
In which context should I use a Semaphore vs an Win Event?
Thanks
| In your case I'd use an event myself. Signal the event when you want the thread to get going. Job done :)
Edit: The difference between semaphores and events comes down to the internal count. If there are multiple ReleaseSemaphores then 2 WaitForSingleObjects will also be released. Events are boolean by nature. If 2 different places Signal event simultaneously then the wait will get released and it will get set back to unsignalled (dependent on if you have automatic or manual resetting). If you need it to be signalled from multiple places simultaneously and for the waiting thread to run twice then this event behaviour could lead to a deadlock.
|
2,810,933 | 2,812,331 | template expressions and visual studio 2005 c++ | I'd like to build the olb3d library with my visual studio 2005 compiler but this failes due to template errors.
To be more specific, the following expression seem to be a problem:
void function(T u[Lattice<T>::d])
On the website of the project is stated that prpably my compiler is not capable of such complicated template expressions - one should use the gcc 3.4.1.
My question is now if there is a way to upgrade my vs c++ compiler so it can handle template expressions on the level as the gcc 3.4.1? Maybe it helps if I get a newer version of visual studio?
Cheers
C.
| The compiler says that it cannot deduce the template type. You can always help it out by specifying the type itself in your code.
foo<int>(some_int_array);
However, the part between [] that is tripping it up is completely meaningless. Arrays decay into pointers and the value is ignored in the first place. You can just comment out that part if this is a real example.
If you take the array by reference, VC++2005 doesn't appear to have any problem with it either:
template <class T>
void function(T (&arr)[Lattice<T>::n]);
(Is it possible that the case that doesn't compile is just so meaningless that no-one ever bothered to check if things like that work?)
|
2,811,130 | 2,812,999 | Is there any reason against directly calling AddRef() inside QueryInterface() implementation? | When implementing IUnknown::QueryInterface() in C++ there're several caveats with pointers manipulation. For example, when the class implements several interfaces (multiple inheritance) explicit upcasts are necessary:
class CMyClass : public IInterface1, public IInterface2 {
};
//inside CMyClass::QueryInterface():
if( iid == __uuidof( IUnknown ) ) {
*ppv = static_cast<IInterface1*>( this ); // upcast in order to properly adjust the pointer
//call Addref(), return S_OK
}
The reason for upcast is quite clear in multiple inheritance scenarios. However every here and there I also see the following:
static_cast<IUnknown*>( *ppv )->AddRef();
instead of simply invoking AddRef() from inside QueryInterface() implementation.
Is there any reason I should do the cast of the value previously copied into ppv instead of just calling AddRef() on the current object?
| AddRef is pure virtual in IUnknown, and none of the other interfaces implement it, so the only implementation in your program is the one you write in CMyClass. That one method overrides both IInterface1::AddRef and IInterface2::AddRef. IUnknown doesn't have any data members (such as a reference count), so the diamond problem doesn't cause your class to be susceptible to a problem such as different calls to AddRef acting on different data in the same class.
Calls to this->AddRef() are going to be routed to the same place as static_cast<IUnknown*>(*ppv)->AddRef(). I see no reason for the more verbose style.
|
2,811,541 | 2,817,496 | Gethostname and IPv6 | Microsoft recommends not to use 'gethostname' on IPv6 and instead use 'getaddrinfo' or 'getnameinfo'.
http://msdn.microsoft.com/en-us/library/ms899604.aspx
But 'gethostname' doesn't seem to have any problem working on IPv6. Does anyone know any reason why 'gethostname' is not recommended on IPv6?
| The main different is the maximum host name length, gethostname() allows 255+1 characters, getnameinfo() supports the full DNS length of 1024+1. If you are using technologies like puny code host names this becomes more pertinent. Other differences are that you are not guaranteed a FQDN when using gethostname().
http://en.wikipedia.org/wiki/Internationalized_domain_name
|
2,811,596 | 2,811,859 | Embedding Python and adding C functions to the interpreter | I'm currently writing an applications that embedds the python interpreter. The idea is to have the program call user specified scripts on certain events in the program. I managed this part but now I want the scripts to be able to call functions in my program.
Here's my code so far:
#include "python.h"
static PyObject* myTest(PyObject* self,PyObject *args)
{
return Py_BuildValue("s","123456789");
}
static PyMethodDef myMethods[] = {{"myTest",myTest},{NULL,NULL}};
int main()
{
Py_Initialize();
Py_InitModule("PROGRAM",myMethods);
PyRun_SimpleString("print PROGRAM.myTest()");
Py_Finalize();
}
Thanks!
| You need to bind that function to some module, see http://docs.python.org/extending/embedding.html#extending-embedded-python
Edit:
Basicly your code should work. Whats not working?
|
2,811,747 | 2,811,843 | boost doesn't bind to member function even using this | I am trying to use boost::bind with a boost::function using this.
It seems a trivial example but I cannot make it work. Can you help me?
Is it because it is not allowed or am I doing something wrong?
// .h
class MyClass{
publc:
void DoSomething(
const std::string& a,
const std::string& b);
void DoABind();
}
//.cpp
void MyClass::DoABind(){
boost::function< void( const std::string& , const std::string& ) > callback(
boost::bind(
&MyClass::DoSomething,
this ));
// this line doesn't compile!!!
}
| I think you want bind(&MyClass::DoSomething, this, _1, _2). I don't have a boost installation to test with though.
|
2,812,079 | 2,812,137 | Compile a shared library statically | I've got a shared library with some homemade functions, which I compile into my other programs, but I have to link the end program with all the libraries I have used to compile the static library. Here is an example:
I have function foo in the library which requires a function from another library libbar.so.
In my main program to use function foo I have to compile it with the -lbar flag. Is there a way I can compile my library statically so it includes all the required code from the other libraries, and I can compile my end program without needing the -lbar flag?
| Shared objects (.so) aren't libraries, they are objects. You can't extract part of them and insert it in other libraries.
What you can do if build a shared object which references the other -- but the other will be needed at run time. Just add the -lbar when linking libfoo.
If you are able to build libbar, you can obviously make a library which is the combination of libfoo and libbar. IIRC, you can also make the linker build a library which is libfoo and the needed part of libbar by linking a .a with the .o meant to go in libbar. Example:
gcc -fPIC -c lib1.c # define foofn(), reference barfn1()
gcc -fPIC -c lib2a.c # define barfn1(), reference barfn2()
gcc -fPIC -c lib2b.c # define barfn2()
gcc -fPIC -c lib2c.c # define barfn3()
gcc -c main.c # reference foofn()
ar -cru libbar.a lib2*.o
gcc -shared -o libfoo.so lib1.o -L. -lbar
nm libfoo.so | grep barfn2() # ok, not here
gcc -o prog main.o -L. -lfoo
env LD_LIBRARY_PATH=. ./prog # works, so foofn(), barfn1() and barfn2() are found
|
2,812,215 | 2,812,248 | Preprocessor directive #ifndef for C/C++ code | In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:
/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif
I think ifndef is saying that if EXAMPLE_H_ isn't defined, define it, which may be useful depending on what tool you are using to compile and link your project. However, I have two questions:
Is this fairly common? I don't see it too often. And is it a good idea to use that rubric, or should you just jump right into defining your code.
What is EXAMPLE_H_ exactly? Why not example.h, or just example? Is there anything special about that, or could is just be an artifact of how eclipse prefers to auto-build projects?
| This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.
Putting the #ifndef wrapper around the contents means the compiler only parses the header's contents once, and avoids redefinition errors.
Some compilers allow "#pragma once" to do the same thing, but the #ifndef construct works everywhere.
|
2,812,338 | 27,240,116 | Reverse PInvoke and create a full unmanaged C# program | I know this is a strange question but the idea is simple: I prefer C# syntax rather than C++:
-Setters and getters directly inside a property
-interfaces
-foreach statement
-possibility to declare an implicit cast operator
other small things...
What I really don't know is if is possible to import a c++ dll (expecially std libraries) in C# if I don't use any namespace (even System)
The idea is just to write a program using everything that you will normally use in C++ (nothing from CLR so), even printf for example
Thanks for any answer
| There's now something close to this
.NET Native compiles C# to native machine code that performs like C++. You will continue to benefit from the productivity and familiarity of the .NET Framework with the great performance of native code.
It's for Windows Store apps only (desktop apps may come in the future):
Desktop apps are a very important part of our strategy. Initially, we are focusing on Windows Store apps with .NET Native. In the longer term we will continue to improve native compilation for all .NET applications.
And
apps will get deployed on end-user devices as fully self-contained natively compiled code (when .NET Native enters production), and will not have a dependency on the .NET Framework on the target device/machine
|
2,812,470 | 2,812,501 | Why does GCC need extra declarations in templates when VS does not? | template<typename T>
class Base
{
protected:
Base() {}
T& get() { return t; }
T t;
};
template<typename T>
class Derived : public Base<T>
{
public:
Base<T>::get; // Line A
Base<T>::t; // Line B
void foo() { t = 4; get(); }
};
int main() { return 0; }
If I comment out lines A and B, this code compiles fine under Visual Studio 2008. Yet when I compile under GCC 4.1 with lines A and B commented, I get these errors:
In member function ‘void Derived::foo()’:
error: ‘t’ was not declared in this scope
error: there are no arguments to ‘get’ that depend on a template parameter, so a declaration of ‘get’ must be available
Why would one compiler require lines A and B while the other doesn't? Is there a way to simplify this? In other words, if derived classes use 20 things from the base class, I have to put 20 lines of declarations for every class deriving from Base! Is there a way around this that doesn't require so many declarations?
| GCC is right in this case, and Visual Studio mistakenly accepts a malformed program. Have a look at the section on Name lookup in the GCC manual. Paraphrasing:
[T]he call to [get()] is not dependent on template arguments (there are no arguments that depend on the type T, and it is also not otherwise specified that the call should be in a [template-]dependent context). Thus a global declaration of such a function must be available, since the one in the base class is not visible until instantiation time.
You can get around this in either of three ways:
The declarations you are already using.
Base<T>::get()
this->get()
(There is also a fourth way, if you want to succumb to the Dark Side:
Using the -fpermissive flag will also let the compiler accept the code, by marking all function calls for which no declaration is visible at the time of definition of the template for later lookup at instantiation time, as if it were a dependent call. We do not recommend using -fpermissive to work around invalid code, and it will also only catch cases where functions in base classes are called, not where variables in base classes are used (as in the example above).
But I would recommend against that, both for the reason mentioned in the manual, and for the reason that your code will still be invalid C++.)
|
2,812,544 | 2,812,586 | C++ Beginner - Trouble using structs and constants! | I am currently working on a simple Scrabble implementation for a college project.
I can't get a part of it to work, though!
Check this out:
My board.h:
http://pastebin.com/J9t8VvvB
The subroutine where the error lies:
//Following snippet contained in board.cpp
//I believe the function is self-explanatory...
//Pos is a struct containing a char, y, a int, x and an orientation, o, which is not //used in this particular case
void Board::showBoard()
{
Pos temp;
temp.o = 0;
for (temp.y = 'A'; temp.y < (65 + TOTAL_COLUMNS); ++temp.y)
{
for (temp.x = 1; temp-x < (1 + TOTAL_ROWS); ++temp.x)
{
cout << _matrix[temp].getContents();
}
cout << endl;
}
}
The errors returned on compile time:
http://pastebin.com/bZv7fggq
How come the error states that I am trying to compare two Pos when I am comparing chars and ints?
I also really can't place these other errors...
Thanks for your time!
EDIT:
Since my whole project depends on Pos, I am going to try overloading the < operator for it... Can anyone give me a few tips on that? Keep in mind, I'm a beginner!
| #define TOTAL_ROWS 15;
#define TOTAL_COLUMNS 15;
Theses are preprocessor definitions, which must not end in a semicolon. The semicolon will become part of the substitution text, so the compiler sees something like (65 + 15;) which is clearly wrong.
In C++, it is better to use const variables instead of #defines. In this case, you could put the following in your Board.cpp:
const unsigned int TOTAL_ROWS = 15;
const unsigned int TOTAL_COLUMNS = 15;
You can then make them available through your header by putting these in Board.h:
extern const unsigned int TOTAL_ROWS;
extern const unsigned int TOTAL_COLUMNS;
Even cleaner is to declare them as class members. Put these in Board.cpp:
const unsigned int Board::TOTAL_ROWS = 15;
const unsigned int Board::TOTAL_COLUMNS = 15;
And in Board.hpp, inside the public section of the class definition:
static const unsigned int TOTAL_ROWS;
static const unsigned int TOTAL_COLUMNS;
They have to be static because they do not belong to any specific Board instance, but are rather properties of the class as a whole. You can then access them from outside the Board class by writing Board::TOTAL_ROWS etc.
The other problem here is that you are creating a map<Pos, Cell>. The map template requires that its key type (Pos) has a valid < operator defined on it; internally, the map sorts its elements using this operator, so it can do fast lookups. The error occurs only at the point where you try to look something up in the map; this is due to the way templates work, so don't break your head over it right now.
One solution is to overload this operator yourself to define an ordering on Pos objects. I would not recommend that to a beginner, because
operator overloading is an advanced technique, and
you have to be very careful to define consistent behaviour, or else the map stars misbehaving, and
if you do this, you should also overload >, <=, and >=, == and !=.
That being said, here is the code. This assumes that two Pos objects with the same x and y values are considered equal; it does not look at the value of o (which is a weird thing to have in a "coordinate" type anyway, and I don't know what it's used for).
bool operator<(Pos const &l, Pos const &r) {
if (l.y < r.y) return true;
if (l.y > r.y) return false;
if (l.x < r.x) return true;
if (l.x > r.x) return false;
return false;
}
The other (better) option is to abandon the Pos type completely, and represent your board as a two-dimensional array, or a vector of vectors. Its type would then be vector<vector<Cell> >. (Note the space between > >! Without it, this will be parsed as the right-shift operator >>!)
|
2,812,760 | 2,812,774 | print TCHAR[] on console | I'm quite sure that it is a stupid issue but it drives me crazy..
how could i print on the console a TCHAR array?
DWORD error = WSAGetLastError();
TCHAR errmsg[512];
int ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, 0, errmsg, 511, NULL);
i need to print errmsg...
| It depends on what TCHAR is. If you compile with Unicode enabled, TCHAR is defined as wchar_t. Then you can use std::wcout, for example:
std::wcout << L"Error: " << errmsg << '\n';
If Unicode is not enabled, TCHAR is an ordinary char and you can use the ordinary std::cout:
std::cout << "Error: " << errmsg << '\n';
|
2,812,875 | 2,812,903 | how const keyword works in c | I want to know about const internals in c and c++ . How compiler imposes constantness ?
Can some one help me please.
| In general const is 100% compiler. When you declare something const, the compiler places restrictions on what it will let you write. It won't let you assign to const scalar, assign through a const reference or or pointer, or invoke a non-const function of const object.
There is no guarantee that the compiler will arrange any sort of runtime protection.
|
2,812,959 | 2,813,000 | How does the where clause in MySQL work? | I have a doubt. Assume R and S are 2 relations with attributes A and B respectively . If I have a query
Select *
From R, S
Where R.A = S.B
Does this work like a double For Loop in say c or c++
For( i=0; i<n; i++)
For( j=0; j<n; j++)
if (i == j)
//DO some work
| First of all: there is no knowing how mysql will internally optimize the query (without knowing the internals of mysql).
In pure relational databases words, this is what you are doing:
SELECT * FROM R, S -> perform cross join, that generates all (r,s) tuples.
WHERE R.A = S.B -> now select those tuples that have this behaviour
So it will go over all tuples (more or less like your code). However, it is perfectly possible mysql will internally reduce this to a more efficient inner join that never creates all tuples but only the tuples where R.A=S.B is valid.
|
2,813,030 | 2,813,107 | yaml-cpp parsing strings | Is it possible to parse YAML formatted strings with yaml-cpp?
There isn't a YAML::Parser::Parser(std::string&) constructor. (I'm getting a YAML string via libcurl from a http-server.)
| Try using a stringstream:
std::string s = "name: YAML from libcurl";
std::stringstream ss(s);
YAML::Parser parser(ss);
|
2,813,045 | 2,813,437 | How to get rid of OCI.dll dependency when compiling static | My application accesses an Oracle database through Qt's QSqlDatabase class.
I'm compiling Qt as static for the release build, but I can't seem to be able to get rid of OCI.dll dependency. I'm trying to link against oci.lib (as available in Oracle's Instant Client with SDK).
Here's my configure line :
configure -qt-libjpeg -qt-zlib -qt-libpng -nomake examples -nomake demos -no-exceptions -no-stl -no-rtti -no-qt3support -no-scripttools -no-openssl -no-opengl -no-phonon -no-style-motif -no-style-cde -no-style-cleanlooks -no-style-plastique -static -release -opensource -plugin-sql-oci -plugin-sql-sqlite -platform win32-msvc2005
I link against oci.h and oci.lib in the SDK's folder by using :
set INCLUDE=C:\oracle\instantclient\sdk\include;%INCLUDE%
set LIB=C:\oracle\instantclient\sdk\lib\msvc;%LIB%
Then, once Qt is compiled, I use the following lines in my *.pro file :
QT += sql
CONFIG += static
LIBS += C:\oracle\instantclient\sdk\lib\msvc\oci.lib
QTPLUGIN += qsqloci
Then, in my main.cpp, I add the following commands to statically compile OCI plugin in the application :
#include <QtPlugin>
Q_IMPORT_PLUGIN(qsqloci)
After compiling the project, I test it on my workstation and it works (as I have Oracle Instant Client installed). When I try on another workstation, I always get the message:
This application has failed to start
because OCI.dll was not found.
Re-installing this application may fix
this problem.
I don't understand why I still need OCI.dll, as my statically linked application is supposed to link to oci.lib instead.
Is there any Qt people here that might have a solution for me ?
Thanks a lot !
STL
| The .lib file you linked is not what you think it is. It is the import library for the DLL, the linker needs it so it knows what functions are implemented by oci.dll. I don't see a static version of the library available from Oracle but didn't look too hard. That's pretty typical for dbase interfaces.
You'll need to follow the deployment instructions for oci.dll, "OCI Instant Client Installation Process" in this document. Changing the PATH, oh joy.
|
2,813,190 | 2,813,361 | Beginner C++ - Trouble using global constants in a header file | Yet another Scrabble project question... This is a simple one.
It seems I am having trouble getting my global constants recognized:
My board.h:
http://pastebin.com/7a5Uyvb8
Errors returned:
1>C:\Users\Francisco\Documents\FEUP\1A2S\PROG\projecto3\projecto3\Board.h(34): error: variable "TOTAL_ROWS" is not a type name
1> vector< vector<Cell> > _matrix(TOTAL_ROWS , vector<Cell>(TOTAL_COLUMNS));
1>
1>main.cpp
1>compilation aborted for .\Game.cpp (code 2)
1>Board.cpp
1>.\Board.h(34): error: variable "TOTAL_ROWS" is not a type name
1> vector< vector<Cell> > _matrix(TOTAL_ROWS , vector<Cell>(TOTAL_COLUMNS));
1> ^
1>
Why does this happen? Why is the compiler expecting types?
Thanks for your time!
EDIT:
Disregard my previous edit...
This is my default constructor:
Board::Board()
{
_matrix(TOTAL_ROWS, vector(TOTAL_COLUMNS));
}
I get the following error.
1>.\Board.cpp(16): error: call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
1> _matrix(TOTAL_ROWS, vector<Cell>(TOTAL_COLUMNS));
1> ^
Why does this happen?
I managed to solve all the problems with my file. I used
Board::Board() :
_matrix(TOTAL_ROWS, vector<Cell>(TOTAL_COLUMNS))
{}
instead. Thanks for all your help!
| The way that is written, you are defining a function called _matrix that returns a vector. So TOTAL_ROWS is expected to be a type name, since it is being parsed as a paramter type. I assume what you are trying to do is define a variable called _matrix that is a vector.
What you want to do is leave off the constructor, and initialize the variable inside your constructor. Only constant integral values can be initialized in the body of the class, at least in the current version of the standard.
Leaving off the unimportant parts:
Board() : _matrix(TOTAL_ROWS, vector<Cell>(TOTAL_COLUMNS)) { }
private:
vector< vector<Cell> > _matrix;
Note that this is just an example. Presumably you have an implementation file with an actual body for Board(), and you should put the initialization there rather than directly in the header or you'll get errors. The important thing is that you should not do it when you declare _matrix initially.
For your new question, extern const unsigned int TOTAL_COLUMNS = 15; defines TOTAL_COLUMNS every time Board.h is included by a file. Constant variables at namespace scope have internal linkage by default, so if you leave off the extern you will be okay.
In general, if the variable isn't constant, you take an approach similar to the one for _matrix. You leave off the initialization in the header, and then inside an implemenation file put it back on:
board.h:
extern const int TOTAL_COLUMNS;
board.cpp:
extern const int TOTAL_COLUMNS = 15;
|
2,813,283 | 2,813,620 | Invalid Argument to getUInt64 when retrieving LAST_INSERT_ID() | I have added a record to my table which auto-increments the primary key. I am having no luck retrieving this new value. The MySQL documents say to use the SELECT LAST_INSERT_ID(); in a query. I have done this, but can't retrieve the results.
According the the metadata of the result set, the data type is BIGINT and the column name is LAST_INSERT_ID(). The C++ connector has a getUInt64() for the result set, which I assume is the correct method to use.
The ResultSet class declaration contains the following:
virtual uint64_t getUInt64(uint32_t columnIndex) const = 0;
virtual uint64_t getUInt64(const std::string& columnLabel) const = 0;
The documentation does not state whether the columnIndex is zero based or one based. I tried both and get sql::InvalidArgumentException for both cases.
Using the result set metadata, I retrieved the column name and passed it directly to the getUInt64 method and still receive the sql::InvalidArgumentException. This not a good indication (when the returned column name doesn't work when fetching the data).
Here is my code fragment:
std::string query_text;
query_text = "SELECT LAST_INSERT_ID();";
boost::shared_ptr<sql::Statement> query(m_db_connection->createStatement());
boost::shared_ptr<sql::ResultSet> query_results(query->executeQuery(query_text));
long id_value = 0;
if (query_results)
{
ResultSetMetaData p_metadata = NULL;
p_metadata = query_results->getMetaData();
unsigned int columns = 0;
columns = p_metadata->getColumnCount();
std::string column_label;
std::string column_name;
std::string column_type;
for (i = 0; i < columns; ++i)
{
column_label = p_metadata->getColumnLabel(i);
column_name = p_metadata->getColumnName(i);
column_type = p_metadata->getColumnTypeName(i);
wxLogDebug("Column label: \"%s\"\nColumn name: \"%s\"\nColumn type: \"%s\"\n",
column_label.c_str(),
column_name.c_str(),
column_type.c_str());
}
unsigned int column_index = 0;
column_index = query_results->findColumn(column_name);
// The value of column_index is 1 (one).
// All of the following will generate sql::InvalidArgumentException
id_value = query_results->getUInt64(column_index);
id_value = query_results->getUInt64(column_name);
id_value = query_results->getUInt64(0);
id_value = query_results->getUInt64(1);
id_record.set_record_id(id_value);
}
Here is the debug output (from wxLogDebug):
10:50:58: Column label: "LAST_INSERT_ID()"
Column name: "LAST_INSERT_ID()"
Column type: "BIGINT"
My Question: How do I retrieve the LAST_INSERT_ID() using the MySQL C++ Connector?
Do I need to use a prepared statement instead?
I am using MySQL Connector C++ 1.0.5 on Windows Vista and Windows XP with Visual Studio 9 (2008).
| Resolved.
I inserted a query_results->next() before retrieving the data and that worked.
|
2,813,672 | 3,891,586 | gcov and switch statements | I'm running gcov over some C code with a switch statement. I've written test cases to cover every possible path through that switch statement, but it still reports a branch in the switch statement as not taken and less than 100% on the "Taken at least once" stat.
Here's some sample code to demonstrate:
#include "stdio.h"
void foo(int i)
{
switch(i)
{
case 1:printf("a\n");break;
case 2:printf("b\n");break;
case 3:printf("c\n");break;
default: printf("other\n");
}
}
int main()
{
int i;
for(i=0;i<4;++i)
foo(i);
return 0;
}
I built with "gcc temp.c -fprofile-arcs -ftest-coverage", ran "a", then did "gcov -b -c temp.c". The output indicates eight branches on the switch and one (branch 6) not taken.
What are all those branches and how do I get 100% coverage?
| I'm using mingw on windows (which is not the latest gcc) and it looks like this may be sorted out in newer versions of gcc.
|
2,813,970 | 2,814,023 | How to modify Keyboard interrupt (under Windows XP) from a C++ Program? |
We have been given a little project (As part of my OS course) to make a Windows program that modifies keyboard input, so that it transforms any lowercase character entered into an uppercase one (without using caps-lock) ! so when you type on the keyboard you'll see what you're typing transformed into uppercase !
I have done this quite easily using Turbo C by calling geninterrupt() and using variables _AH, _AL, i had to read a character using:
_AH = 0x07; // Reading a character without echo
geninterrupt(0x21); // Dos interrupt
Then to transform it into an Upercase letter i have to mask the 5th bit by using:
_AL = _AL & 0xDF; // Masking the entered character with 11011111
and then i will display the character using any output routine.
Now, this solution will only work under old C DOS compilers. But what we intend to do is to make a close or similar solution to this by using any modern C/C++ compiler under Windows XP ! What i have first thought of is modifying the Keyboard ISR so that it masks the fifth bit of any entered character to turn it uppercase ! But i do not know how exactly to do this. Second, I wanted to create a Win32 console program to either do the same solution (but to no avail) or make a windows-compatible solution, still i do not know which functions to use !
Third I thought to make a windows program that modifies the ISR directly to suit my needs ! and i'm still looking for how to do this !
So please, If you could help me out on this, I would greatly appreciate it !
Thank you in advance !
(I'm using Windows XP on intel X86 with mingw-GCC compiler.)
| You can't get access to the Keyboard ISR unless you write a Ring 0 device driver. You are better off investigating the Windows Hook APIs. These accomplish the same thing.
Start here: http://msdn.microsoft.com/en-us/library/ms644990%28v=VS.85%29.aspx
|
2,814,013 | 2,814,892 | Double Free inside of a destructor upon adding to a vector | Hey, I am working on a drum machine, and am having problems with vectors.
Each Sequence has a list of samples, and the samples are ordered in a vector. However, when a sample is push_back on the vector, the sample's destructor is called, and results in a double free error.
Here is the Sample creation code:
class XSample
{
public:
Uint8 Repeat;
Uint8 PlayCount;
Uint16 Beats;
Uint16 *Beat;
Uint16 BeatsPerMinute;
XSample(Uint16 NewBeats,Uint16 NewBPM,Uint8 NewRepeat);
~XSample();
void GenerateSample();
void PlaySample();
};
XSample::XSample(Uint16 NewBeats,Uint16 NewBPM,Uint8 NewRepeat)
{
Beats = NewBeats;
BeatsPerMinute = NewBPM;
Repeat = NewRepeat-1;
PlayCount = 0;
printf("XSample Construction\n");
Beat = new Uint16[Beats];
}
XSample::~XSample()
{
printf("XSample Destruction\n");
delete [] Beat;
}
And the 'Dynamo' code that creates each sample in the vector:
class XDynamo
{
public:
std::vector<XSample> Samples;
void CreateSample(Uint16 NewBeats,Uint16 NewBPM,Uint8 NewRepeat);
};
void XDynamo::CreateSample(Uint16 NewBeats,Uint16 NewBPM,Uint8 NewRepeat)
{
Samples.push_back(XSample(NewBeats,NewBPM,NewRepeat));
}
Here is main():
int main()
{
XDynamo Dynamo;
Dynamo.CreateSample(4,120,2);
Dynamo.CreateSample(8,240,1);
return 0;
}
And this is what happens when the program is run:
Starting program: /home/shawn/dynamo2/dynamo
[Thread debugging using libthread_db enabled]
XSample Construction
XSample Destruction
XSample Construction
XSample Destruction
*** glibc detected *** /home/shawn/dynamo2/dynamo: double free or corruption (fasttop): 0x0804d008 ***
However, when the delete [] is removed from the destructor, the program runs perfectly.
What is causing this? Any help is greatly appreciated.
| The problem is you are dynamically allocating memory in your object but not declaring a copy constructor/ assignment operator. When you allocate memory and are responsible for deleting it you need to define all FOUR methods that the compiler generates.
class XSample
{
public:
// Pointer inside a class.
// This is dangerous and usually wrong.
Uint16 *Beat;
};
XSample::XSample(Uint16 NewBeats,Uint16 NewBPM,Uint8 NewRepeat)
{
// You allocated it here.
// But what happens when you copy this object or assign it to another variable.
Beat = new Uint16[NewBeats];
}
XSample::~XSample()
{
// Delete here. Turns into double delete if you don't have
// copy constructor or assignment operator.
delete [] Beat;
}
What happens to the above when you do:
XSample a(15,2,2);
XSample b(a); // Copy constructor called.
XSample c(15,2,2);
c = a; // Assignment operator called.
Two ways to solve this:
Create the copy constructor/assignment operator.
Use another object that does memory management for you.
I would use solution 2 (as it is simpler).
Its also a better design. Memory management should be done by their own class and you should concentreate on your drums.
class XSample
{
public:
std::vector<Uint16> Beat;
};
XSample::XSample(Uint16 NewBeats,Uint16 NewBPM,Uint8 NewRepeat):
Beat(NewBeats)
{
// Notice the vector is constructed above in the initializer list.
}
// Don't need this now.
XSample::~XSample()
{
}
If you want to do it the hard way:
Dynamically allocating an array of objects
If you want to see what the compiler versions look here:
C++ implicit copy constructor for a class that contains other objects
|
2,814,164 | 2,814,284 | Differences between Static & Dynamic data structures | What are the main differences, advantages and disadvantages between static and dynamic data structures?
Under which categories do the most common data structures fall?
How could I know in which situation to use each?
| To start with an oversimplification:
There are just a few basic kinds of data structures: arrays, lists and trees. Everything else can be composed by using different types of these two structures (e.g. a hash table can be implemented with an array for the hash values and one list for each hash value to handle collisions).
Of these structures, arrays are static (i.e., their memory footprint does not vary over time as operations are performed on them) and everything else is dynamic (i.e., in the general case the memory footprint changes).
The differences between the two kinds of structures can be derived from the above:
Static needs the maximum size to be known in advance, while dynamic can adapt on the fly
Static does not reallocate memory no matter what, so you can have guaranteed memory requirements
There are also other differences, which however only come into play if your data might be sorted. I can't give an extensive list, as there are many dynamic data structures which exhibit different performance characteristics for different operations ("add", "remove", "find") and so they cannot be placed all under the same roof.
A very visible difference is that sorted arrays require moving (possibly a lot of) stuff around in memory for any operation other than "find", while dynamic structures generally perform less work.
So, to recap:
If you need a guarantee on maximum memory usage, you have no option other than an array.
If you have a hard upper limit for your data size, consider using an array. Arrays can be a good fit for problems which mainly require add/remove operations (keep the array unsorted) and for those which mainly require find operations (keep the array sorted), but not for both at the same time.
If you do not have a hard upper limit, or if you require all of add/remove/find to be fast, use an appropriate kind of dynamic structure.
Edit: I did not mention graphs, another kind of dynamic data structure which arguably cannot be composed from simpler parts (by definition, a tree has exactly one link going "into" any node except the root, while graphs may have more than one). However, graphs cannot really be compared with other structures in a "what would be better to use" scenario, because you either need to use a graph or you do not (other structures may exhibit different performance, but in the end they all support the same set of operations).
|
2,814,188 | 2,814,216 | C++ Array of pointers: delete or delete []? | Cosider the following code:
class Foo
{
Monster* monsters[6];
Foo()
{
for (int i = 0; i < 6; i++)
{
monsters[i] = new Monster();
}
}
virtual ~Foo();
}
What is the correct destructor?
this:
Foo::~Foo()
{
delete [] monsters;
}
or this:
Foo::~Foo()
{
for (int i = 0; i < 6; i++)
{
delete monsters[i];
}
}
I currently have the uppermost constructor and everything is working okey, but of course I cannot see if it happens to be leaking...
Personally, I think the second version is much more logical considering what I am doing. Anyway, what is the "proper" way to do this?
| delete[] monsters;
Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.
Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.
Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)
|
2,814,347 | 2,814,584 | How to take snapshot in linux - programmatically C++ | I am currently involved in a project which requires me to repeatedly take snapshots of the screen. I am using qt's grabScreen function to do the same.
The screen freezes for half a second every time the program takes a snapshot causing the computer to seem to be very slow :(
Can anybody suggest me a better method of doing this ?
| You could look at the source of, say, ksnapshot which is the Qt-based KDE app doing this. Its SVN archive is here.
|
2,814,512 | 2,814,620 | Understanding C++ pointers (when they point to a pointer) | I think I understand references and pointers pretty well. Here is what I (think I) know:
int i = 5; //i is a primitive type, the value is 5, i do not know the address.
int *ptr; //a pointer to an int. i have no way if knowing the value yet.
ptr = &i; //now i have an address for the value of i (called ptr)
*ptr = 10; //Go to the value in ptr, use it to find a location and store 10 there
Please feel free to comment or correct these statements.
Now I'm trying to make the jump to arrays of pointers. Here is what I do not know:
char **char_ptrs = new char *[50];
Node **node_ptrs = new Node *[50];
My understanding is that I have 2 arrays of pointers, one set of pointers to chars and one to nodes. So if I wanted to set the values, I would do something like this:
char_ptrs[0] = new char[20];
node_ptrs[0] = new Node;
Now I have a pointer, in the 0 position of my array, in each respective array. Again, feel free to comment here if I'm confused.
So, what does the ** operator do? Likewise, what is putting a single * next to the instantiation doing (*[50])? (what is that called exactly, instantiation?)
| A few comments:
*ptr = 10; // Doesn't need to "go get" the value. Just overwrites it.
Also:
char **char_ptrs = new char *[50];
Node **node_ptrs = new Node *[50];
It is easier to think that you have two arrays. However, technically (and as far as the compiler is concerned) what you have is two pointers. One is a pointer to a (pointer to a char) and the other is a pointer to a (pointer to a node).
This is easily seen by the declarations of your variables, which, by the way, can be most easily read right-to-left:
char **char_ptrs
Reading right to left: char_ptrs is a pointer to a pointer to char
Putting a * next to a pointer is properly called dereferencing that pointer. Since arrays do not technically exist, operator [] on arrays is also a dereferencing operation: arr[i] is another way of writing *(arr + i). To properly understand this, you need to be familiar with pointer arithmetic.
More than one consecutive *s: each one dereferences the result of the expression it operates on. So when writing:
char c = **char_ptrs;
what happens is:
char_ptrs is a pointer to a pointer to a char. Dereferencing it once (for the rightmost *) gets you its value, which is a pointer to a char. Dereferencing that value (for the leftmost *) gives you its own value in turn, which is a char. In the end, c contains the value of the char stored in memory at the place where the pointer pointed to by char_ptrs (in other words, the first pointer in your array) points.
Conversely, if you write **char_ptrs = 'a'; then you are changing the value in that memory location.
|
2,814,582 | 2,814,706 | Newbie: Render RGB to GTK widget -- howto? | Big picture: I want to render an RGB image via GTK on a linux box.
I'm a frustrated GTK newbie, so please forgive me.
I assume that I should create a Drawable_area in which to render the image -- correct?
Do I then have to create a graphics context attached to that area? How?
my simple app (which doesn't even address the rgb issue yet is this:
int main(int argc, char** argv) {
GdkGC * gc = NULL;
GtkWidget * window = NULL;
GtkDrawingArea * dpage = NULL;
GtkWidget * page = NULL;
gtk_init( &argc, & argv );
window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
page = gtk_drawing_area_new( );
dpage = GTK_DRAWING_AREA( page );
gtk_widget_set_size_request( page, PAGE_WIDTH, PAGE_HEIGHT );
gc = gdk_gc_new( GTK_DRAWABLE( dpage ) );
gtk_widget_show( window );
gtk_main();
return (EXIT_SUCCESS);
}
my dpage is apparently not a 'drawable' (though it is a drawing area). I am confused as to a) how do I get/create the graphics context which is required in subsequent function calls?
b) am I close to a solution, or am I so completely *#&@& wrong that there is no hope
c) a baby steps tutorial. (I started with hello world as my base, so I got that far).
any and all help appreciated.
bp
| You should go through the scribble tutorial at least ( http://library.gnome.org/devel/gtk-tutorial/stable/c2422.html ), if not the larger tutorial of which this a part.
Since you tagged your question c++, I'd recommend using gtkmm, you'll find it much easier to develop in if you already know C++ pretty well. There is a tutorial for it as well: http://library.gnome.org/devel/gtkmm-tutorial/stable/
|
2,814,779 | 2,814,845 | Program crashes in debugger before anything happens | I'm building an application for Windows XP using the MinGW tool chain and it sometimes crashes unexpectedly. So, I'm trying to use a debugger (Gdb) but the program exits with code 03 before anything happens. In fact, all I see from GDB is:
[New thread 3184.0x7b8][New thread
3184.0xef8]
Program exited with code 03.
My suspicion is that there is some failed dynamic linking of a dependency (which are Qt, VTK, and ITK, all built with MinGW). However, this does not happen when I just run the program normally. Or if it happens, it appears to be intermittent and well after the program is launched and running. NOTE: I'm also using Cmake for cross compiling.
What should I do? What can I try?
| Add a callback via signal(SIGABRT, <callback>) to catch the call to abort before it shuts down the process. If this happens before you hit main() you might have to resort to a static global and compiler trickery to catch it.
|
2,814,798 | 2,814,856 | OpenGL constant don't exist | I haven't got GL_GENERATE_MIPMAP_HINT, GL_GENERATE_MIPMAP constatns, why ? I have old version of opengl ? Where can I download new library version ?
| From here: http://www.opengl.org/wiki/Getting_started#OpenGL_2.0.2B_and_extensions
For Linux: http://www.opengl.org/registry/api/glext.h
For GLX: http://www.opengl.org/registry/api/glxext.h
For Windows: http://www.opengl.org/registry/api/wglext.h
|
2,814,858 | 2,814,923 | Select all points in a matrix within 30m of another point | So if you look at my other posts, it's no surprise I'm building a robot that can collect data in a forest, and stick it on a map. We have algorithms that can detect tree centers and trunk diameters and can stick them on a cartesian XY plane.
We're planning to use certain 'key' trees as natural landmarks for localizing the robot, using triangulation and trilateration among other methods, but programming this and keeping data straight and efficient is getting difficult using just Matlab.
Is there a technique for sub-setting an array or matrix of points? Say I have 1000 trees stored over 1km (1000m), is there a way to say, select only points within 30m radius of my current location and work only with those?
I would just use a GIS, but I'm doing this in Matlab and I'm unaware of any GIS plugins for Matlab.
I forgot to mention, this code is going online, meaning it's going on a robot for real-time execution. I don't know if, as the map grows to several miles, using a different data structure will help or if calculating every distance to a random point is what a spatial database is going to do anyway.
I'm thinking of mirroring the array of trees, into two arrays, one sorted by X and the other by Y. Then bubble sorting to determine the 30m range in that. I do the same for both arrays, X and Y, and then have a third cross link table that will select the individual values. But I don't know, what that's called, how to program that and I'm sure someone already has so I don't want to reinvent the wheel.
Cartesian Plane
GIS
| The simple solution of calculating all the distances and scanning through seems to run almost instantaneously:
lim = 1;
num_trees = 1000;
trees = randn(num_trees,2); %# list of trees as Nx2 matrix
cur = randn(1,2); %# current point as 1x2 vector
dists = hypot(trees(:,1) - cur(1), trees(:,2) - cur(2)); %# distance from all trees to current point
nearby = tree_ary((dists <= lim),:); %# find the nearby trees, pull them from the original matrix
On a 1.2 GHz machine, I can process 1 million trees (1 MTree?) in < 0.4 seconds.
Are you running the Matlab code directly on the robot? Are you using the Real-Time Workshop or something? If you need to translate this to C, you can replace hypot with sqr(trees[i].x - pos.x) + sqr(trees[i].y - pos.y), and replace the limit check with < lim^2. If you really only need to deal with 1 KTree, I don't know that it's worth your while to implement a more complicated data structure.
|
2,815,317 | 2,815,363 | Launch IE with specific BHO enabled | I have a IE BHO plugin that I only want to be enabled when the user launches IE from my program (The program starts IE using CreateProcess()).
I don't want this BHO to be enabled when a user launches IE from outside my program, as that would mean any problems in the BHO could potentially mess up the user's normal browsing experience.
What's the best way to do this?
One way would be to register the BHO, launch IE and then quickly unregister the BHO. This seems kind of messy though, as a crash in the program that launches IE could cause the BHO to remain registered.
| Your approach is very error-prone, I advise against it. Instead, your BHO should always load with IE, but by default it should do nothing. What you need then is a way to tell it "start filtering" or "start recording" or whatever.
You've got lots of choices from there. The simplest is a flag somewhere in the environment (a semaphore, a disk file). You can have a special url, like mybho:start that it watches for.
I've done this many times, it works.
Edit Yes, the BHO will be loaded into memory, together with any DLLs it depends on (though you can wait and load them only when needed via LoadLibrary()).
|
2,815,320 | 2,815,330 | run a function every x seconds in c++ | I'm trying to build a feed reader in C++, so I need the program to check for new feeds intermittently. However, the user needs still to be able to interact with the program, so the suggestion that I seem to keep finding, to have the system wait, doesn't work for me. Can anyone suggest a better solution, say a timer that runs in the background or something?
Thanks,
Charles
| You can create a thread that sleeps for the specific time period. This is OS independent. Or, if you are programming in windows, you can set a timer to send a timeout event periodically. The use of timers depends on your deployment platform.
|
2,815,589 | 2,815,626 | operator "new" returning a non-local heap pointer for only one class? | Language : C++
Platform : Windows Server 2003
I have an exe calling a DLL.
EDIT :
(exe is not doing anything, it calls few global function which does everything related to DLL within DLL. It does not explicitly new any of DLL classes)
I allocate (new) the memory for class A within the DLL, it returns me a non-local heap pointer.
I tried to new other classes within the DLL (which are in DLL), "new" returns a valid heap pointer for them, its only Class A which is not being allocated properly.
I am on windows and validating the heap by this function call :
EDIT:
ClassA* pA = new ClassA();
_CrtIsValidHeapPointer ( (const void *) pA )
I am seriously confused why this only happens with new-ing Class A and no other class ?
(All Native Code)
FINAL EDIT :
it turned out to be a bad build. can't get it to reproduce in the new one... wasted 5 days on this :'(
| Export only global functions from DLLs and call only exported functions and through v-tables. Your problem is only one of many caused by trying to export entire classes. DLLs aren't the same as .so libraries.
EDIT: Since the question now reveals that the class isn't exported, but all of this is observed inside the single DLL, going to suggest other possible causes.
Is the same pointer returned from new being tested, or could it be a pointer to a base sub-object? Did the allocation use new or new []? Either of these could cause the pointer to point into the middle of a heap block instead of the start.
|
2,815,667 | 2,826,761 | libmcrypt and MS Visual C++ | Has anyone tried using libmcrypt and visual c++? I was trying to use Crypto++ but it seems not fully compatible - and I need to decrypt data encrypted in PHP using linux libmcrypt.
I found only cygwin version of libmcrypt but no .lib files or header.
I'm using RIJNDAEL_128 - maybe there is easier way to decrypt it in Visual C++?
Thanks
| I finally found a working libmcrypt version compatible with Visual Studio
It is here http://files.edin.dk/php/win32/mcrypt/dev/ and worked correctly.
|
2,815,746 | 2,815,918 | Formatting an integer in C++ | I have an 8 digit integer which I would like to print formatted like this:
XXX-XX-XXX
I would like to use a function that takes an int and returns a string.
What's a good way to do this?
| This is how I'd do it, personally. Might not be the fastest way of solving the problem, and definitely not as reusable as egrunin's function, but it strikes me as both clean and easy to understand. I'll throw it in the ring as an alternative to the mathier and loopier solutions.
#include <sstream>
#include <string>
#include <iomanip>
std::string format(long num) {
std::ostringstream oss;
oss << std::setfill('0') << std::setw(8) << num;
return oss.str().insert(3, "-").insert(6, "-");
};
|
2,815,792 | 2,815,907 | How do I get started on a bigger project? | Most of the time I have been programming little apps either for myself or for the benifit of learning. Now that my programming skills are considered somewhat intermediate, I was wondering how I would tackle a large programming project.
Lets suppose I wanted to make an application that has a lot of features and is intended for the use of others and not just myself; how do I go about planning for such projects?
Do I just jump in and start coding the thing or is there some sort of recommended process?
Thanks in advance :D
| Although Steve has a good recommendation, I think that answer is probably a bit beyond where you are at.
The "simplified" version of how to go beyond what you've been doing is:
gather requirements from the users. Write them down in terms of required functionality.
Do simple screen layouts. The main part here is just to get functionality grouped into the right areas.
Build a data model
Build the actual screens and tie them to the data model.
Iterate with more features.
At each point stop and do a reality check. For example, do the screens make sense? Is the information organized in a good way? What areas might you have a problem in? etc.
Above all, stay in communication with the people that will actually use this product.
Also, their are two keys to a successful project. The first is to break it down into manageable portions. In other words break it up so that you can deliver each piece quickly, call that piece done, and move to the next. This will help you to stay focused and not get in over your head.
Second, work with what you know. When moving up, refrain from taking this as an opportunity to expand your coding skills. Instead, your focus here is going to be on learning project management.
After you've done one or two iterations of this, then look into the various software development methodologies such as scrum, waterfall, etc and see what they have to offer you.
Good luck!
|
2,815,900 | 17,053,089 | Find location using only distance and bearing? | Triangulation works by checking your angle to three KNOWN targets.
"I know the that's the Lighthouse of Alexandria, it's located here (X,Y) on a map, and it's to my right at 90 degrees." Repeat 2 more times for different targets and angles.
Trilateration works by checking your distance from three KNOWN targets.
"I know the that's the Lighthouse of Alexandria, it's located here (X,Y) on a map, and I'm 100 meters away from that." Repeat 2 more times for different targets and ranges.
But both of those methods rely on knowing WHAT you're looking at.
Say you're in a forest and you can't differentiate between trees, but you know where key trees are. These trees have been hand picked as "landmarks."
You have a robot moving through that forest slowly.
Do you know of any ways to determine location based solely off of angle and range, exploiting geometry between landmarks? Note, you will see other trees as well, so you won't know which trees are key trees. Ignore the fact that a target may be occluded. Our pre-algorithm takes care of that.
1) If this exists, what's it called? I can't find anything.
2) What do you think the odds are of having two identical location 'hits?' I imagine it's fairly rare.
3) If there are two identical location 'hits,' how can I determine my exact location after I move the robot next. (I assume the chances of having 2 occurrences of EXACT angles in a row, after I reposition the robot, would be statistically impossible, barring a forest growing in rows like corn). Would I just calculate the position again and hope for the best? Or would I somehow incorporate my previous position estimate into my next guess?
If this exists, I'd like to read about it, and if not, develop it as a side project. I just don't have time to reinvent the wheel right now, nor have the time to implement this from scratch. So if it doesn't exist, I'll have to figure out another way to localize the robot since that's not the aim of this research, if it does, lets hope it's semi-easy.
| What you're looking for is Monte Carlo localization (also known as a particle filter). Here's a good resource on the subject.
Or nearly anything from the probabilistic robotics crowd, Dellaert, Thrun, Burgard or Fox. If you're feeling ambitious, you could try to go for a full SLAM solution - a bunch of libraries are posted here.
Or if you're really really ambitious, you could implement from first principles using Factor Graphs.
|
2,815,915 | 2,815,931 | what is better when creating new variable in a loop in c++ | What is the best way in C++ to use std::map in loops ?
dynamically allocated
stack allocated
Code:
for(int i=0;i<3;i++)
{
std::map<int,int>* m = new std::map<int,int>;
//or ...
std::map<int,int> m;
}
| Avoid new unless you really need it, i.e. the variable/structure has a lifetime unrelated to any calling scope. (If it "belongs" to the calling function, return by value.)
This is clearly not such a case. The second, preferable, example is called a local variable.
I would be making a choice between
for(int i=0;i<3;i++)
{
std::map<int,int> m;
…
}
and
std::map<int,int> m;
for(int i=0;i<3;i++)
{
…
m.clear();
}
The latter may perform better when the container is std::vector by reusing allocated memory. With map the difference is only style.
|
2,816,201 | 2,826,591 | C++ return type overload hack | I was bored and came up with such hack (pseudocode):
1 struct proxy {
2 operator int(); // int function
3 operator double(); // double function
4 proxy(arguments);
5 arguments &arguments_;
6 };
7
8 proxy function(arguments &args) {
9 return proxy(args);
10 }
11 int v = function(...);
12 double u = function(...);
is it evil to use in real code?
my possible usage scenario is for example product of array elements, which may/may not overflow:
int size(short *array);
short size(short *array);
The reason for function, in case you use templates, than template parameters can be inferred from function arguments
| I'd rather use template specialization, just feels less "hacky" and probably will be faster (no object creation, although of course that can be optimized away by smart compiler).
But anyway, I'd rather see code like
template<typename T> T function();
template<> int function() {
return 1;
}
template<> float function() {
return 1.0;
}
....
int a = function<int>();
float b = function<float>();
Nothing wrong with your code though, especially if you stay away from numeric types/pointers since otherwise unanticipated effects might occur, rules of conversion is quite complicated in C++.
|
2,816,229 | 2,816,533 | Can I un-check a group of RadioBottoms inside a group box? | radio bottoms inside a group Box will be treated as a group of bottoms. They are mutual exclusive. How can I clean up their check states??
I have several radio bottoms, one of them are checked.
How can I "clean" (uncheck) all radio bottoms??
"setChecked" doesn't work within a group, I tried to do following things but failed.
My code is as following, radioButtom is inside a groupBox, and I want to unchecked it.
The first setChecked does works, but the second one doesn't, the radioBottom doesn't been unchecked
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QRadioButton *radioButton;
ui->setupUi(this);
radioButton->setChecked(true);
radioButton->setChecked(false);
}
Where is the problem in my code?
| The trick is to disable the autoExclusive property before unchecking it, then re-enabling it.
ui->radioButton->setChecked(true);
ui->radioButton->setAutoExclusive(false);
ui->radioButton->setChecked(false);
ui->radioButton->setAutoExclusive(true);
After this, the radioButton is unchecked.
|
2,816,285 | 2,816,480 | Classes with the same name - is it restricted only within the same translation unit? | Let's just I had the following code:
foo.h
class Foo
{
// ...
};
foo.cpp
#include "foo.h"
// Functions for class Foo defined here...
Let's say that Foo are built into a static library foo.lib.
Now let's say I have the following:
foo2.h
class Foo
{
// ...
};
foo2.cpp
#include "foo2.h"
// Functions for class Foo defined here...
This is built into a separate static library foo2.lib.
Now, if I re-link foo.lib and foo2.lib into an executable program foo.exe, should it be complaining that class Foo has been defined twice?
In my experiences, neither the compiler or the linker are complaining.
I wouldn't be expecting the compiler to complain, because they have been defined in separate translation units.
But why doesn't the linker complain?
How does the linker differentiate between the 2 versions of the Foo class? Does it work by decorating the symbols?
| You can have more than one definition of a class type in multiple translation units subject to some fairly strong restrictions meaning that the definitions must be virtually identical. (3.2 [basic.def.odr])
This also applies to enumeration types, inline functions with external linkage, class template, non-static function template, static data member of a class template, member function of a class template or a template specialization for which some template parameters are not specified.
What this effectively means is that you can follow the common practice of putting a class definition in a header file and using this in multiple translation units so long as there aren't any differences in the include sequence that would cause the token sequence or meaning of any names used in the class definition to differ between the multiple translation units.
What you can't have is more than one definition of a non-inline member function of a class across the whole program.
Violations of either of these rules causes undefined behaviour so no part of the compile sequence is required to generate a diagnostic or cause any particular behaviour so if you have two definitions of a class that are slightly different things my appear to work or may cause strange issues at runtime.
It is very likely that if you have two definitions of a non-inline member function of an identically named class with and identical signature that you will have errors at link time but this isn't a language guarantee.
It's worth noting that if two definitions for the same entities are in separate object files in libraries (either the same or difference libraries) it is likely that your program will not actually include more than one definition for a given entity. The way linkers traditionally work is that the iteratively select object files that help resolve symbols in the program but they leave out object files that don't help resolve symbols. This means that after the first object file with a definition is included there is no need to include the second object file with an alternative definition.
|
2,816,293 | 2,816,317 | Passing optional parameter by reference in c++ | I'm having a problem with optional function parameter in C++
What I'm trying to do is to write function with optional parameter which is passed by reference, so that I can use it in two ways (1) and (2), but on (2) I don't really care what is the value of mFoobar.
I've tried such a code:
void foo(double &bar, double &foobar = NULL)
{
bar = 100;
foobar = 150;
}
int main()
{
double mBar(0),mFoobar(0);
foo(mBar,mFoobar); // (1)
cout << mBar << mFoobar;
mBar = 0;
mFoobar = 0;
foo(mBar); // (2)
cout << mBar << mFoobar;
return 0;
}
but it crashes at
void foo(double &bar, double &foobar = NULL)
with message :
error: default argument for 'double& foobar' has type 'int'
Is it possible to solve it without function overloading?
| The default argument of a (mutable) reference must be an l-value. The best I can think of, without overloading, is
static double _dummy_foobar;
void foo(double &bar, double &foobar = _dummy_foobar)
|
2,816,415 | 2,822,474 | List of header file locations for the Havok Physics Engine | I am trying to integrate the Havok physics engine into my small game. It is a really nice SDK, but the header files are all over the place. Many headers are deeply nested in multiple directories. That gets confusing when you are trying to include headers for different important objects.
I would like to know if there is a nice guide that will let you know where certian objects are and what headres they are in. I have already looked at Havok's documentation, and I also looked at the reference manual, but they don't give great detail as to where certain classes are located (header location). Also, is there any programs out there that can scan header files and create a list of where objects can be found?
Thanks again
| In Visual Studio, right-clicking on a class and selecting Go to Declaration usually does a good job of finding the header. You can could also add the source directory to your list of directories to search for Find in Files. Once you've got the header open, you can copy the file path and convert it to a #include statement.
FYI, in general, this forum on Intel's site is a better place than SO for Havok-specific questions. I check there regularly, as do several of the developer support engineers from Havok.
|
2,816,752 | 2,816,811 | Can a member struct be zero-init from the constructor initializer list without calling memset? | Let's say I have the following structure declaration (simple struct with no constructor).
struct Foo
{
int x;
int y;
int z;
char szData[DATA_SIZE];
};
Now let's say this struct is a member of a C++ class as follows:
class CFoobar
{
Foo _foo;
public:
CFoobar();
};
If I declare CFoobar's constructor as follows:
CFoobar::CFoobar()
{
printf("_foo = {%d, %d, %d}\n", _foo.x, _foo.y,_foo.z);
for (int x = 0; x < 100; x++)
printf("%d\n", _foo.szData[x]);
}
As you would expect, when CFoobar's constructor runs, garbage data gets printed out Obviously, the easy fix is to memset or ZeroMemory &_foo. It's what I've always done...
However, I did notice that if add _foo to the constructor's initialization list with no parameters as follows:
CFoobar::CFoobar()
: _foo()
{
That this appears to zero-out the member variables of _foo. At least that was the case with g++ on linux.
Now here's my question: Is this standard C++, or is this compiler specific behavior?
If it's standard behavior, can someone quote me a reference from an official source? Any "gotchas" in regards to implicit zero-init behavior with more complicated structs and classes?
| Yes, this is defined behaviour according to the standard. 12.6.2 [class.base.init] / 3 : "if the expression-list of the mem-initializer is omitted, the base class or member subobject is value-initialized."
Be warned, though, if Foo wasn't a POD-type but still had no user-declared constructor (e.g. it had a std::string type) then some very popular compilers would not correctly value-initialize it.
All compilers that I know of do correctly perform value-initialization of POD members when you use () as the initializer in a constructor initializer-list.
|
2,816,971 | 2,817,136 | C++ String tokenisation from 3D .obj files | I'm pretty new to C++ and was looking for a good way to pull the data out of this line.
A sample line that I might need to tokenise is
f 11/65/11 16/70/16 17/69/17
I have a tokenisation method that splits strings into a vector as delimited by a string which may be useful
static void Tokenise(const string& str, vector<string>& tokens, const string& delimiters = " ")
The only way I can think of doing it is to tokenise with " " as a delimiter, remove the first item from the resulting vector, then tokenise each part by itself. Is there a good way to do this all in one?
| I see the question is tagged as C++ but the absolutely easiest way to do this is with scanf
int indices[3][3];
sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &indices[0][0], &indices[0][1],...);
|
2,817,019 | 2,845,811 | OpenCV (c++) multi channel element access | I'm trying to use the "new" 2.0 c++ version of OpenCV, but everything is else like in simple C version. I have some problem with changing the values in image.
The image is CV_8UC3.
for (int i=0; i<image.rows; i++)
{
for (int j=0; j<image.cols; j++)
{
if (someArray[i][j] == 0)
{
image.at<Vec3i>(i,j)[0] = 0;
image.at<Vec3i>(i,j)[1] = 0;
image.at<Vec3i>(i,j)[2] = 0;
}
}
}
It's not working. What am I doing wrong???
Thank you!
| Shouldn't you be using Vec3b instead of Vec3i ?
CV_8UC3 means your image is 8 bit, 3 channels, unsigned char. While Vec3iis for 3 channels integers and Vec3bis for 3 channels unsigned char.
So I think you should be using Vec3b
|
2,817,139 | 2,817,939 | Game loop in Win32 API | I'm creating game mario like in win32 GDI . I've implemented the new loop for game :
PeekMessage(&msg,NULL,0,0,PM_NOREMOVE);
while (msg.message!=WM_QUIT)
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else // No message to do
{
gGameMain->GameLoop();
}
}
But my game just running until I press Ctrl + Alt + Del ( mouse cursor is rolling ).
| I've always been using something like that:
MSG msg;
while (running){
if (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
try{
onIdle();
}
catch(std::exception& e){
onError(e.what());
close();
}
}
onIdle is actual game lopp implementation, onError() is an error handler (takes error description as argument), and "running" is either a global bool variable or a class member. Setting "running" to false shuts down the game.
|
2,817,222 | 2,824,521 | Multithreaded SDL error in C++ | I'm building a program in C++, using SDL, and am occasionally receiving this error:
* glibc detected * ./assistant: double free or corruption (!prev)
It's difficult to replicate, so I can't find exactly what's causing it, but I just added a second thread to the program, and neither thread run on its own seems to cause the error.
The threads don't share any variables, though they both run the functions SDL_BlitSurface and SDL_Flip. Could running these concurrently throw up such an error, or am I barking up the wrong tree?
If this is the cause, should I simply throw a mutex around all SDL calls?
| Turns out that it was being caused by the threads not terminating correctly. Instead of terminating them from main, I allowed them to return when they saw that main had finished running (through a global 'running' variable), and the problem disappeared.
|
2,817,274 | 2,842,051 | Vim OmniCppComplete on vectors of pointers | I might have done something wrong in the set up but is OmniCppComplete supposed to provide the members/functions of classes when doing this?
vectorofpointers[0]->
At the moment all I get when trying that are things relating to the vector class itself, which obviously isn't very useful. I think it might have been working before I tagged /usr/include/ but I could be wrong.
Also, is it possible to disable the preview window? I find it just clutters up my workspace. And since I enabled ShowPrototypeInAbbr I don't really need it.
Thanks,
Alex
| I do not think it is possible to get proper code completion on the objects that are included in the vector, but someone please correct me if I am mistaken.
To disable the preview window, make sure to not set preview for the the completeopt option, type :help completeopt in Vim for more information.
|
2,818,416 | 2,820,251 | cygwin does not contain mysql.h .. How can i get it in cygwin? | I need mysql.h for my c++ program.
| The main reason MySQL isn't already in the Cygwin package repository is that there's little point in running the MySQL server under Cygwin, as that would only slow it down and not provide any compensating benefit.
All you actually need, though, is the C API client library. It's easy enough to build it yourself.
First, download the source code tarball from mysql.com.
Then at a Cygwin prompt, say:
$ tar xvzf /wherever/it/is/mysql-5.1.46.tar.gz
$ cd mysql-5.1.46
$ ./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var \
--infodir=/usr/share/info --mandir=/usr/share/man \
--disable-shared --without-{debug,readline,libedit,server}
$ make
$ make install
That should build and install just the C client library parts, which should let your other code build.
The most critical part of that configure command is the --without-* bit. Without that, it tries to build everything, which didn't work last time I tried it. You can't blame MySQL, Inc, for not patching Cygwin-specific bugs in the server, since you'd want to use the native binaries instead. There's no problem running a client linked to the Cygwin C library against a fully-native server, any more than there is running client and server on two entirely different OSes across a network.
Incidentally, after you get the C library up and running, you might want to look at MySQL++. (Disclaimer: I'm MySQL++'s primary maintainer.)
|
2,819,059 | 2,819,105 | Preallocating memory with C++ in realtime environment | I'm having a function which gets an input buffer of n bytes, and needs an auxillary buffer of n bytes in order to process the given input buffer.
(I know vector is allocating memory at runtime, let's say that I'm using a vector which uses static preallocated memory. Imagine this is NOT an STL vector.)
The usual approach is
void processData(vector<T> &vec) {
vector<T> &aux = new vector<T>(vec.size()); //dynamically allocate memory
// process data
}
//usage:
processData(v)
Since I'm working in a real time environment, I wish to preallocate all the memory I'll ever need in advance.
The buffer is allocated only once at startup. I want that whenever I'm allocating a vector, I'll automatically allocate auxillary buffer for my processData function.
I can do something similar with a template function
static void _processData(vector<T> &vec,vector<T> &aux) {
// process data
}
template<size_t sz>
void processData(vector<T> &vec) {
static aux_buffer[sz];
vector aux(vec.size(),aux_buffer); // use aux_buffer for the vector
_processData(vec,aux);
}
// usage:
processData<V_MAX_SIZE>(v);
However working alot with templates is not much fun (now let's recompile everything since I changed a comment!), and it forces me to do some bookkeeping whenever I use this function.
Are there any nicer designs around this problem?
| I don't see how you can get precisely what you describe. Something like this could be a good compromise for you.
void processData(vector<T>& vec)
{
static vector<T> aux(vec.size());
if (vec.size() > aux.size()) {
aux.resize(vec.size());
}
...
}
|
2,819,205 | 2,819,265 | Multithreaded Multiplication of Large Non-sparse, Non-square Matrices in C/C++ | All,
I'm looking for recommendations for C or C++ libraries (preferably open source) that use multi-threaded techniques to multiply large, non-square, (e.g. 65536xn in size where n < 65536) non-sparse matrices. Thanks.
-&&
| Intel MKL (not open source)
AMD ACML (free, but not open source)
GOTO BLAS (free for academic use, IIRC, and you get the source, but not "open source")
ATLAS BLAS (open source)
|
2,819,245 | 2,819,287 | Is std::pair<int, std::string> ordering well-defined? | It seems that I can sort a std::vector<std::pair<int, std::string>>, and it will sort based on the int value. Is this a well defined thing to do?
Does std::pair have a default ordering based on its elements?
| std::pair uses lexicographic comparison: It will compare based on the first element. If the values of the first elements are equal, it will then compare based on the second element.
The definition in the C++03 standard (section 20.2.2) is:
template <class T1, class T2>
bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y);
Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second).
|
2,819,521 | 2,820,729 | Dynamic-linked DLL needs to share a global variable with its caller | I have a static library libStatic that defines a global variable like this
Header file libStatic/globals.h:
extern int globvar;
Code file libStatic/globals.cpp:
int globvar = 42;
The DLL libDynamic and the executable runner are using this global variable. Furtheron, libDynamic is linked at run-time into runner (via LoadLibrary(), GetProcAddress(), and the works...)
I understand this will lead to globvar being created twice, once in the heap of runner and once in the heap of libDynamic, which is of course very undesirable.
Is there a good away around this? How can I ensure that libDynamic and runner are using the same globvar?
| An easy way would be to let the .DLL point to the global variable of the executable. Right after loading you would call a special function inside that library (something like SetGlobVar(int*)). That way the library will always point to the same global variable as the .EXE.
|
2,819,558 | 2,820,862 | Looking to reimplement build toolchain from bash/grep/sed/awk/(auto)make/configure to something more sane (e.g. boost.build, etc) | I currently maintain a few boxes that house a loosely related cornucopia of coding projects, databases and repositories (ranging from a homebrew *nix distro to my class notes), maintained by myself and a few equally pasty-skinned nerdy friends (all of said cornucopia is stored in SVN).
The vast majority of our code is in C/C++/assembly (a few utilities are in python/perl/php, we're not big java fans), compiled in gcc. Our build toolchain typically consists of a hodgepodge of make, bash, grep, sed and awk. Recent discovery of a Makefile nearly as long as the program it builds (as well as everyone's general anxiety with my cryptic sed and awking) has motivated me to seek a less painful build system.
Currently, the strongest candidate I've come across is Boost Build/Bjam as a replacement for GNU make and python as a replacement for our build-related bash scripts. Are there any other C/C++/asm build systems out there worth looking into? I've browsed through a number of make alternatives, but I haven't found any that are developed by names I know aside from Boost's.
(I should note that an ability to easily extract information from svn commandline tools such as svnversion is important, as well as enough flexibility to configure for builds of asm projects as easily as c/c++ projects)
| You could use python-based build system, too -- http://code.google.com/p/waf/
|
2,819,600 | 2,819,664 | std::string insert method has ambiguous overloads? | Environment: VS2005 C++ using STLPort 5.1.4.
Compiling the following code snippet:
std::string copied = "asdf";
char ch = 's';
copied.insert(0,1,ch);
I receive an error:
Error 1 error C2668: 'stlpx_std::basic_string<_CharT,_Traits,_Alloc>::insert' : ambiguous call to overloaded function
It appears that the problem is the insert method call on the string object.
The two defined overloads are
void insert ( iterator p, size_t n, char c );
string& insert ( size_t pos1, size_t n, char c );
But given that STLPort uses a simple char* as its iterator, the literal zero in the insert method in my code is ambiguous.
So while I can easily overcome the problem by hinting such as
copied.insert(size_t(0),1,ch);
My question is: is this overloading and possible ambiguity intentional in the specification? Or more likely an unintended side-effect of the specific STLPort implementation?
(Note that the Microsoft-supplied STL does not have this problem as it has a class for the iterator, instead of a naked pointer)
| Known issue, ruled "Not A Defect". http://std.dkuug.dk/jtc1/sc22/wg21/docs/lwg-closed.html#84
|
2,819,937 | 3,462,187 | Invalidating non-client areas | I've a window which has custom border/caption, in order to do that I handle WM_NCPAINT message. My caption has two backgrounds a brighter one for the active window, and a darker one for the background window.
But under some circumstances, for example when the window loses/gain focus, my caption is not updated so I end with the wrong background.
Until now I've handled WM_NCACTIVATE, and send a RedrawWindow(hwnd, NULL, NULL, RDW_FRAME|RDW_INVALIDATE), but this causes the whole window to repaint. Do you have any advice about this?
| Overriding non-client area is always fraught with peril. It seems the Window manager makes a lot of assumptions for optimization. Clearly it can be done, see Office, but it might take a lot of experimentation.
Just an idea. Call RedrawWindow twice, once to invalidate the non-client area then again to validate the client area.
RedrawWindow(hwnd, NULL, NULL, RDW_FRAME | RDW_INVALIDATE);
RedrawWindow(hwnd, NULL, NULL, RDW_NOFRAME | RDW_VALIDATE);
Another idea is to try to paint just the frame immediately, without invalidating anything:
RedrawWindow(hwnd, NULL, NULL, RDW_FRAME | RDW_UPDATENOW | RDW_NOCHILDREN);
Yet another idea is to specify an empty RECT or HREGION in the 2nd or 3rd parameters. It might not invalidate the client area that way.
|
2,819,994 | 2,820,182 | How to split the definition of template friend function within template class? | The following example compiles fine but I can't figure out how to separate declaration and definition of operator<<() is this particular case.
Every time I try to split the definition friend is causing trouble and gcc complains the operator<<() definition must take exactly one argument.
#include <iostream>
template <typename T>
class Test {
public:
Test(const T& value) : value_(value) {}
template <typename STREAM>
friend STREAM& operator<<(STREAM& os, const Test<T>& rhs) {
os << rhs.value_;
return os;
}
private:
T value_;
};
int main() {
std::cout << Test<int>(5) << std::endl;
}
Operator<<() is supposed to have a free first parameter to work with different kind of output streams (std::cout, std::wcout or boost::asio::ip::tcp::iostream). The second parameter should be bound to a specialized version of the surrounding class.
Test<int> x;
some_other_class y;
std::cout << x; // works
boost::asio::ip::tcp::iostream << x; // works
std::cout << y; // doesn't work
boost::asio::ip::tcp::iostream << y; // works
Besides that using a non-member-function isn't equivalent to splitting the definition and declaration because non-member-functions can't access private attributes the the class.
| The easiest is probably to make all these template operators friends:
#include <iostream>
template <typename T>
class Test
{
public:
Test(const T& value) : value_(value) {}
template <typename STREAM, typename U>
friend STREAM& operator<<(STREAM& os, const Test<U>& rhs);
private:
T value_;
};
template <typename STREAM, typename T>
STREAM& operator<<( STREAM& os, const Test<T>& rhs )
{
os << rhs.value_;
return os;
}
|
2,820,206 | 2,820,224 | fstream file I/O question - when to close a file stream | I am trying to work out if I need to call close on a fstream object if the intial open failed.
i.e.
std::fstream strm;
strm.open( "filename" );
if( ! strm.fail() )
{
// Do something
strm.close(); // [1]
}
strm.close(); // [2]
Where should close be called here - should it always be called [2] or only if the open succeeds[1]?
I may be going over the top here, but coming from the Windows API way of typically doing this I have CloseHandle( ... ); embedded in my mind :-)
| The stream will be automatically closed by the fstream's destructor - there is no need to close it explicitly, unless your program logic demands it, for example if you are going to re-open it. However, closing a stream that didn't open won't cause any problems.
|
2,820,221 | 2,820,289 | Why was std::strstream deprecated? | I recently discovered that std::strstream has been deprecated in favor of std::stringstream. It's been a while since I've used it, but it did what I needed to do at the time, so was surprised to hear of its deprecation.
My question is why was this decision made, and what benefits does std::stringstream provide that are absent from std::strstream?
| The strstream returned a char * that was very difficult to manage, as nowhere was it stated how it had been allocated. It was thus impossible to know if you should delete it or call free() on it or do something else entirely. About the only really satisfactory way to deallocate it was to hand it back to the strstream via the freeze() function. This was sufficiently non-obvious, that lots of people got it wrong. The stringstream returns a string object which manages itself, which is far less error prone.
There was also the issue of having to use ends to terminate the string, but I believe the deallocation problem was the main reason for deprecation.
|
2,820,285 | 2,820,393 | abort, terminate or exit? | What's the difference between those three, and how shall I end program in case of exception which I can't handle properly?
| My advice would be not to use any of them. Instead, catch the exceptions you can't handle in main() and simply return from there. This means that you are guaranteed that stack unwinding happens correctly and all destructors are called. In other words:
int main() {
try {
// your stuff
}
catch( ... ) {
return 1; // or whatever
}
}
|
2,820,367 | 2,820,452 | Qt/C++ regular expression library with unicode property support | I'm converting an application from the .Net framework to Qt using C++. The application makes extensive use of regular expression unicode properties, i.e. \p{L}, \p{M}, etc. I've just discovered that the QRegExp class lacks support for this among other things (lookbehinds, etc.)
Can anyone recommend a C++ regular expression library that:
Supports unicode properties
Is unicode-aware in other respects (i.e. \w matches more than ASCII word characters)
As a bonus, supports lookbehinds.
Please don't point me to the wikipedia article; I don't trust it. That article says that QRegExp supports unicode properties. Unless I'm really doing something wrong, it doesn't. I'm looking for someone actually using unicode properties with a regex library in a project.
| http://site.icu-project.org/
ICU is a mature, widely used set of
C/C++ and Java libraries providing
Unicode and Globalization support for
software applications.
released under a nonrestrictive open source license
...
Regular Expression: ICU's regular expressions fully support Unicode
while providing very competitive
performance.
It's also compatible to Boost, see their statement in this regard.
|
2,820,477 | 2,820,521 | Class members allocation on heap/stack? | If a class is declared as follows:
class MyClass
{
char * MyMember;
MyClass()
{
MyMember = new char[250];
}
~MyClass()
{
delete[] MyMember;
}
};
And it could be done like this:
class MyClass
{
char MyMember[250];
};
How does a class gets allocated on heap, like if i do MyClass * Mine = new MyClass();
Does the allocated memory also allocates the 250 bytes in the second example along with the class instantiation? And will the member be valid for the whole lifetime of MyClass object?
As for the first example, is it practical to allocate class members on heap?
| Yes, yes, and yes.
Your first example has a bit of a bug in it, though: which is that because it one of its data members is a pointer with heap-allocated data, then it should also declare a copy-constructor and assignment operator, for example like ...
MyClass(const MyClass& rhs)
{
MyMember = new char[250];
memcpy(MyMember, rhs.MyMember, 250);
}
|
2,820,558 | 2,820,604 | copying program arguments to a whitespace separated std::string | I have a Visual Studio 2008 C++ application where I would like to copy all of program arguments in to a string separated by a whitespace " ". i.e., if my program is called as foo.exe \Program Files, then my folder string below would contain \Program Files
Below is an example of what I'm doing now. I was wondering if there was a shorter or easier method of doing this. Is there an easy way to eliminate the std::wstringstream variable?
int _tmain( int argc, _TCHAR* argv[] )
{
std::wstringstream f;
std::copy( argv + 1,
argv + argc,
std::ostream_iterator< std::wstring, wchar_t >( f, L" " ) );
std::wstring folder = f.str();
// ensure the folder begins with a backslash
if( folder[ 0 ] != L'\\' )
folder.insert( 0, 1, L'\\' );
// remove the trailing " " character from the end added by the std::copy() above
if( *folder.rbegin() == L' ')
folder.erase( folder.size() - 1 );
// ...
}
Thanks,
PaulH
| How about this:
int main(int argc, char* argv[])
{
std::string path;
if(argc < 2)
{
std::cout << "Not enough arguments" << std::endl;
return;
}
path = argv[1]; // Assignment works from char* types
// Do the rest of your folder manipulation below here
}
That should work. Even with the main() function declared as it is now, it should still work from a TCHAR (I think), or you can change main's declaration to a more "standard" main() declaration.
|
2,820,608 | 2,820,655 | Is correct name enough to make it happen? | I've just dipped into limits.h by Microsoft. I tried to check what's the return type for max() function and to my surprise I see something like this:
// TEMPLATE CLASS numeric_limits
template<class _Ty>
class numeric_limits
: public _Num_base
{ // numeric limits for arbitrary type _Ty (say little or nothing)
public:
static _Ty (__CRTDECL min)() _THROW0()
{ // return minimum value
return (_Ty(0));
}
static _Ty (__CRTDECL max)() _THROW0()
{ // return maximum value
return (_Ty(0));//EXACTLY THE SAME WHAT IN min<<------------------
}
//... other stuff
};
How is it possible that in both min and max return exactly the same? Does it mean that if I would write makeSanwich() return (_Ty(0)) it would make a sandwich for me? How is it possible that having this same code with just the function names different we are getting different results?
| This is implemented through template specialization. Probably, you'll find something like this elsewhere:
template<>
class numeric_limits<int> : public _Num_base {
public:
static int min() {
return INT_MIN;
}
static int max() {
return INT_MAX;
}
};
If you use numeric_limits<int> the above specialization will be preferred over the general case. There are similar specializations for float, char etcetera.
Only if none of these match, the general case will be selected. In that case, the compiler will try to construct an object of type _Ty from the 0 constant. Why that is ever useful... I don't know. I would rather have a compilation error instead.
|
2,820,621 | 2,822,064 | Why aren't unsigned OpenMP index variables allowed? | I have a loop in my C++/OpenMP code that looks like this:
#pragma omp parallel for
for(unsigned int i=0; i<count; i++)
{
// do stuff
}
When I compile it (with Visual Studio 2005) I get the following error:
error C3016: 'i' : index variable in OpenMP 'for' statement must have signed integral type
I understand that the error occurs because i is unsigned instead of signed, and changing i to be signed removed this error. What I want to know is why is this an error? Why aren't unsigned index variables allowed? Looking at the MSDN page for this error gives me no clues.
| According to the OpenMP 2.0 C/C++ API specification (pdf), section 2.4.1, that's one of the restrictions of the for loop. No reason is given for it, but I suspect it's just to simplify the assumptions that the code and compiler have to make, since there's special code to ensure that the range doesn't overflow the maximum value of the type.
OpenMP 3.0 apparently allows for unsigned types too, but I haven't seen it in action yet.
|
2,820,646 | 2,820,713 | Using std::ifstream to load in an array of struct data type into a std::vector | I am working on a bitmap loader in C++ and when moving from the C style array to the std::vector I have run into an usual problem of which Google does not seem to have the answer.
8 Bit and 4 bit, bitmaps contain a colour palette. The colour palette has blue, green, red and reserved components each 1 byte in size.
// Colour palette
struct BGRQuad
{
UInt8 blue;
UInt8 green;
UInt8 red;
UInt8 reserved;
};
The problem I am having is when I create a vector of the BGRQuad structure I can no longer use the ifstream read function to load data from the file directly into the BGRQuad vector.
// This code throws an assert failure!
std::vector<BGRQuad> quads;
if (coloursUsed) // colour table available
{ // read in the colours
quads.reserve(coloursUsed);
inFile.read( reinterpret_cast<char*>(&quads[0]), coloursUsed * sizeof(BGRQuad) );
}
Does anyone know how to read directly into the vector without having to create a C array and copy data into the BGRQuad vector?
| You need to use quads.resize(coloursUsed) in place of quads.reserve(coloursUsed). Reserve just sets the capacity of the vector object but does not allocate memory. Resize will actually allocate the memory.
|
2,820,882 | 2,823,258 | Vehicle 2 Vehicle Communication Questions | I have a rare opportunity to meet the man in charge of implementing vehicle 2 vehicle communication for the US Department of Transportation with 2 others in a few hours.
Do YOU have any questions for him?
I know this is a little outside the normal, but this is a 'reverse' thread and I felt he has some great knowledge on the subject that I want to share with this community.
I'll post his answers later today to his questions.
Ask about V2V implementation, privacy issues, use cases, or if you've thought of a great way to use V2V and want me to share it with him, he can at least think about it. He is in charge of panel that creates the standard. Or anything else...
I'm more interested in sharing great uses for V2V if you can think of any... I'll give credit, promise... particularly because he may not hear them on a day to day basis.
Here's a good primer on the subject if you want to contribute something original.
http://www.popularmechanics.com/technology/gadgets/news/4213544
| The guy came and delivered a presentation. Every question I had from you guys he covered. If I didn't answer correctly, please let me know.
Most information can be found here: http://www.intellidriveusa.org/
|
2,821,012 | 2,821,337 | How to write curiously recurring templates with more than 2 layers of inheritance? | All the material I've read on Curiously Recurring Template Pattern seems to one layer of inheritance, ie Base and Derived : Base<Derived>. What if I want to take it one step further?
#include <iostream>
using std::cout;
template<typename LowestDerivedClass> class A {
public:
LowestDerivedClass& get() { return *static_cast<LowestDerivedClass*>(this); }
void print() { cout << "A\n"; }
};
template<typename LowestDerivedClass> class B : public A<LowestDerivedClass> {
public: void print() { cout << "B\n"; }
};
class C : public B<C> {
public: void print() { cout << "C\n"; }
};
int main()
{
C c;
c.get().print();
// B b; // Intentionally bad syntax,
// b.get().print(); // to demonstrate what I'm trying to accomplish
return 0;
}
How can I rewrite this code to compile without errors and display
C
B
Using c.get().print() and b.get().print() ?
Motivation: Suppose I have three classes,
class GuiElement { /* ... */ };
class Window : public GuiElement { /* ... */ };
class AlertBox : public Window { /* ... */ };
Each class takes 6 or so parameters in their constructor, many of which are optional and have reasonable default values. To avoid the tedium of optional parameters, the best solution is to use the Named Parameter Idiom.
A fundamental problem with this idiom is that the functions of the parameter class have to return the object they're called on, yet some parameters are given to GuiElement, some to Window, and some to AlertBox. You need a way to write this:
AlertBox box = AlertBoxOptions()
.GuiElementParameter(1)
.WindowParameter(2)
.AlertBoxParameter(3)
.create();
Yet this would probably fail because, for example, GuiElementParameter(int) probably returns GuiElementOptions&, which doesn't have a WindowParameter(int) function.
This has been asked before, and the solution seems to be some flavor of the Curiously Recurring Template Pattern. The particular flavor I use is here.
It's a lot of code to write every time I create a new Gui Element though. I've been looking for ways to simplify it. A primary cause of complexity is the fact that I'm using CRTP to solve the Named-Parameter-Idiom problem, but I have three layers not two (GuiElement, Window, and AlertBox) and my current workaround quadruples the number of classes I have. (!) For example, Window, WindowOptions, WindowBuilderT, and WindowBuilder.
That brings me to my question, wherein I'm essentially looking for a more elegant way to use CRTP on long chains of inheritance, such as GuiElement, Window, and Alertbox.
| Here is what I've settled on, using a variation on CRTP's to solve the problem presented in my motivation example. Probably best read starting at the bottom and scrolling up..
#include "boost/smart_ptr.hpp"
using namespace boost;
// *** First, the groundwork....
// throw this code in a deep, dark place and never look at it again
//
// (scroll down for usage example)
#define DefineBuilder(TYPE, BASE_TYPE) \
template<typename TargetType, typename ReturnType> \
class TemplatedBuilder<TYPE, TargetType, ReturnType> : public TemplatedBuilder<BASE_TYPE, TargetType, ReturnType> \
{ \
protected: \
TemplatedBuilder() {} \
public: \
Returns<ReturnType>::me; \
Builds<TargetType>::options; \
template<typename TargetType>
class Builds
{
public:
shared_ptr<TargetType> create() {
shared_ptr<TargetType> target(new TargetType(options));
return target;
}
protected:
Builds() {}
typename TargetType::Options options;
};
template<typename ReturnType>
class Returns
{
protected:
Returns() {}
ReturnType& me() { return *static_cast<ReturnType*>(this); }
};
template<typename Tag, typename TargetType, typename ReturnType> class TemplatedBuilder;
template<typename TargetType> class Builder : public TemplatedBuilder<TargetType, TargetType, Builder<TargetType> > {};
struct InheritsNothing {};
template<typename TargetType, typename ReturnType>
class TemplatedBuilder<InheritsNothing, TargetType, ReturnType> : public Builds<TargetType>, public Returns<ReturnType>
{
protected:
TemplatedBuilder() {}
};
// *** preparation for multiple layer CRTP example *** //
// (keep scrolling...)
class A
{
public:
struct Options { int a1; char a2; };
protected:
A(Options& o) : a1(o.a1), a2(o.a2) {}
friend class Builds<A>;
int a1; char a2;
};
class B : public A
{
public:
struct Options : public A::Options { int b1; char b2; };
protected:
B(Options& o) : A(o), b1(o.b1), b2(o.b2) {}
friend class Builds<B>;
int b1; char b2;
};
class C : public B
{
public:
struct Options : public B::Options { int c1; char c2; };
private:
C(Options& o) : B(o), c1(o.c1), c2(o.c2) {}
friend class Builds<C>;
int c1; char c2;
};
// *** many layer CRTP example *** //
DefineBuilder(A, InheritsNothing)
ReturnType& a1(int i) { options.a1 = i; return me(); }
ReturnType& a2(char c) { options.a2 = c; return me(); }
};
DefineBuilder(B, A)
ReturnType& b1(int i) { options.b1 = i; return me(); }
ReturnType& b2(char c) { options.b2 = c; return me(); }
};
DefineBuilder(C, B)
ReturnType& c1(int i) { options.c1 = i; return me(); }
ReturnType& c2(char c) { options.c2 = c; return me(); }
};
// note that I could go on forever like this,
// i.e. with DefineBuilder(D, C), and so on.
//
// ReturnType will always be the first parameter passed to DefineBuilder.
// ie, in 'DefineBuilder(C, B)', ReturnType will be C.
// *** and finally, using many layer CRTP builders to construct objects ***/
int main()
{
shared_ptr<A> a = Builder<A>().a1(1).a2('x').create();
shared_ptr<B> b = Builder<B>().a1(1).b1(2).a2('x').b2('y').create();
shared_ptr<B> c = Builder<C>().c2('z').a1(1).b1(2).a2('x').c1(3).b2('y').create();
// (note: any order works)
return 0;
};
|
2,821,223 | 2,821,244 | How would one call std::forward on all arguments in a variadic function? | I was just writing a generic object factory and using the boost preprocessor meta-library to make a variadic template (using 2010 and it doesn't support them). My function uses rval references and std::forward to do perfect forwarding and it got me thinking...when C++0X comes out and I had a standard compiler I would do this with real variadic templates. How though, would I call std::forward on the arguments?
template <typename ...Params>
void f(Params... params) // how do I say these are rvalue reference?
{
y(std::forward(...params)); //? - I doubt this would work.
}
Only way I can think of would require manual unpacking of ...params and I'm not quite there yet either. Is there a quicker syntax that would work?
| You would do:
template <typename ...Params>
void f(Params&&... params)
{
y(std::forward<Params>(params)...);
}
The ... pretty much says "take what's on the left, and for each template parameter, unpack it accordingly."
|
2,821,439 | 2,821,461 | C++ class derivation and superconstructor confusion | Hey, in a tutorial C++ code, I found this particular piece of confusion:
PlasmaTutorial1::PlasmaTutorial1(QObject *parent, const QVariantList &args)
: Plasma::Applet(parent, args), // <- Okay, Plasma = namespace, Applet = class
m_svg(this), // <- A member function of class "Applet"?
m_icon("document") // <- ditto?
{
m_svg.setImagePath("widgets/background");
// this will get us the standard applet background, for free!
setBackgroundHints(DefaultBackground);
resize(200, 200);
}
I'm not new to object oriented programming, so class derivation and super-classes are nothing complicated, but this syntax here got me confused.
The header file defines the class like this:
class PlasmaTutorial1 : public Plasma::Applet
{
Similar to above, namespace Plasma and class Applet. But what's the public doing there?
I fear that I already know the concept but don't grasp the C++ syntax/way of doing it.
In this question I picked up that these are called "superconstructors", at least that's what stuck in my memory, but I don't get this to the full extend.
If we glance back at the first snippet, we see Constructor::Class(...) : NS::SuperClass(...), all fine 'till here. But what are m_svg(this), m_icon("document") doing there? Is this some kind of method to make these particular functions known to the derivated class?
Is this part of C++ basics or more immediate? While I'm not completly lost in C++, I feel much more at home in C :)
Most of the OOP I have done so far was done in D, Ruby or Python. For example in D I would just define class MyClass : MySuperClass, override what I needed to and call the super class' constructor if I'd need to.
Okay, after reading some of the answers, is this...
PlasmaTutorial1::PlasmaTutorial1(QObject *parent, const QVariantList &args)
: Plasma::Applet(parent, args), // <- Call the _parent_ constructor
m_svg(this), // <- set m_svg (in the _derived_ class) to "this"
m_icon("document") // <- set m_icon (in the _derived_ class) to "document"
{
...
}
...assumption correct?
Test's confirm my assumption so far. Thanks a lot! Picking a winning answer is a hard choice, tho...
| What you are seeing is a initialization list. They are encouraged by the C++ FAQ Lite and speed up member initialization, because your members don't need to take default values before entering the constructor.
|
2,821,807 | 2,822,091 | global counter in application: bad practice? | In my C++ application I sometimes create different output files for troubleshooting purposes. Each file is created at a different step of our pipelined operation and it's hard to know file came before which other one (file timestamps all show the same date).
I'm thinking of adding a global counter in my application, and a function (with multithreading protection) which increments and returns that global counter. Then I can use that counter as part of the filenames I create.
Is this considered bad practice? Many different modules need to create files and they're not necessarily connected to each other.
| I think, adding to file name current system time with high enough precision will be cleaner and easier to implement and maintain
//helper function to encapsulate details
string makeFileName(string filename)
{ return filename + getCurrentTime(); }
void MyClass::SomeMethod()
{
File f = CreateFile(makeFileName("myclassfile"));
...
}
|
2,821,859 | 2,826,578 | Specialization of a member of a template class for a template class parameter type | I have a templated class Matrix. I want to specialize a function for the type complex, where T can be anything. I have tried this :
6 template <typename T>
7 class Matrix {
8 public :
9 static void f();
10 };
11 template<typename T> void Matrix<T>::f() { cout << "generic" << endl; }
12 template<> void Matrix<double>::f() { cout << "double" << endl; }
13 template<typename T> void Matrix<std::complex<T> >::f() { cout << "complex" << endl; }
Line 13 does not compile. How can I do that ?
| In fact, I found a clever way to do it through Boost. Since I don't want my library to be dependant on Boost, here is the code :
template <class T, T val> struct integral_constant
{
typedef integral_constant<T, val> type;
typedef T value_type;
static const T value = val;
};
typedef integral_constant<bool, true> true_type;
typedef integral_constant<bool, false> false_type;
template <typename T> struct is_complex : false_type{};
template <typename T> struct is_complex<std::complex<T> > : true_type{};
template <typename T>
class Matrix {
public :
static void f() { f_( typename is_complex<T>::type() ); }
private :
static void f_( true_type ) { cout << "generic complex" << endl; }
static void f_( false_type ) { cout << "generic real" << endl; }
};
template<> void Matrix<double>::f() { cout << "double" << endl; }
This way, I can use function overloading and template to achievement my goal.
|
2,822,016 | 2,822,039 | how to activate 'more' option on command prompt (visual studio) | My code dumps a hell amount of data on the command prompt. How do I activate the 'MORE' option for the output so that I see the output page by page? (MS Visual Studio)
For eg. Matlab has the command 'more on' to do the same!
Thanks.
| With the Windows command prompt you can append | more to your command, e.g.,
dir | more
|
2,822,139 | 2,822,180 | breadth first or depth first search | I know how this algorithm works, but cant decide when to use which algorithm ?
Are there some guidelines, where one better perform than other or any considerations ?
Thanks very much.
| If you want to find a solution with the shortest number of steps or if your tree has infinite height (or very large) you should use breadth first.
If you have a finite tree and want to traverse all possible solutions using the smallest amount of memory then you should use depth first.
If you are searching for the best chess move to play you could use iterative deepening which is a combination of both.
IDDFS combines depth-first search's space-efficiency and breadth-first search's completeness (when the branching factor is finite).
|
2,822,146 | 2,822,176 | References and Object Slicing | I don't have my Effective C++ with me and this is bugging me so much that I have to ask for my own sanity. Given
class Foo : public Bar{}
void MyFunc(Bar &_input);
If I pass in a Foo, am I tangling with the slicing problem or have I avoided it?
| Not a problem, because you're passing in a reference. You're not creating a new object, just letting MyFunc access the original object.
|
2,822,243 | 2,822,280 | Store return value of function in reference C++ | Is it valid to store the return value of an object in a reference?
class A { ... };
A myFunction()
{
A myObject;
return myObject;
} //myObject goes out of scope here
void mySecondFunction()
{
A& mySecondObject = myFunction();
}
Is it possible to do this in order to avoid copying myObject to mySecondObject? myObject is not needed anymore and should be exactly the same as mySecondObject so it would in theory be faster just to pass ownership of the object from one object to another. (This is also possible using boost shared pointer but that has the overhead of the shared pointer.)
Thanks in advance.
| It is not allowed to bind the temporary to a non-const reference, but if you make your reference const you will extend the lifetime of the temporary to the reference, see this Danny Kalev post about it.
In short:
const A& mySecondObject = myFunction();
|
2,822,272 | 2,822,533 | How can I return an object into PHP userspace from my extension? | I have a C++ object, Graph, which contains a property named cat of type Category. I'm exposing the Graph object to PHP in an extension I'm writing in C++.
As long as the Graph's methods return primitives like boolean or long, I can use the Zend RETURN_*() macros (e.g. RETURN_TRUE(); or RETURN_LONG(123);. But how can I make
Graph->getCategory();
return a Category object for the PHP code to manipulate?
I'm following the tutorial over at http://devzone.zend.com/article/4486, and here's the Graph code I have so far:
#include "php_getgraph.h"
zend_object_handlers graph_object_handlers;
struct graph_object {
zend_object std;
Graph *graph;
};
zend_class_entry *graph_ce;
#define PHP_CLASSNAME "WFGraph"
ZEND_BEGIN_ARG_INFO_EX(php_graph_one_arg, 0, 0, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(php_graph_two_args, 0, 0, 2)
ZEND_END_ARG_INFO()
void graph_free_storage(void *object TSRMLS_DC)
{
graph_object *obj = (graph_object*)object;
delete obj->graph;
zend_hash_destroy(obj->std.properties);
FREE_HASHTABLE(obj->std.properties);
efree(obj);
}
zend_object_value graph_create_handler(zend_class_entry *type TSRMLS_DC)
{
zval *tmp;
zend_object_value retval;
graph_object *obj = (graph_object*)emalloc(sizeof(graph_object));
memset(obj, 0, sizeof(graph_object));
obj->std.ce = type;
ALLOC_HASHTABLE(obj->std.properties);
zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_copy(obj->std.properties, &type->default_properties, (copy_ctor_func_t)zval_add_ref, (void*)&tmp, sizeof(zval*));
retval.handle = zend_objects_store_put(obj, NULL, graph_free_storage, NULL TSRMLS_CC);
retval.handlers = &graph_object_handlers;
return retval;
}
PHP_METHOD(Graph, __construct)
{
char *perspectives;
int perspectives_len;
Graph *graph = NULL;
zval *object = getThis();
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &perspectives, &perspectives_len) == FAILURE) {
RETURN_NULL();
}
graph = new Graph(perspectives);
graph_object *obj = (graph_object*)zend_object_store_get_object(object TSRMLS_CC);
obj->graph = graph;
}
PHP_METHOD(Graph, hasCategory)
{
long perspectiveId;
Graph *graph;
graph_object *obj = (graph_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
graph = obj->graph;
if (graph == NULL) {
RETURN_NULL();
}
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &perspectiveId) == FAILURE) {
RETURN_NULL();
}
RETURN_BOOL(graph->hasCategory(perspectiveId));
}
PHP_METHOD(Graph, getCategory)
{
// what to do here?
RETURN_TRUE;
}
function_entry php_getgraph_functions[] = {
PHP_ME(Graph,__construct,NULL,ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(Graph,hasCategory,php_graph_one_arg,ZEND_ACC_PUBLIC)
PHP_ME(Graph,getCategory,php_graph_one_arg,ZEND_ACC_PUBLIC)
{ NULL, NULL, NULL }
};
PHP_MINIT_FUNCTION(getgraph)
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, PHP_CLASSNAME, php_getgraph_functions);
graph_ce = zend_register_internal_class(&ce TSRMLS_CC);
graph_ce->create_object = graph_create_handler;
memcpy(&graph_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
graph_object_handlers.clone_obj = NULL;
return SUCCESS;
}
zend_module_entry getgraph_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
PHP_GETGRAPH_EXTNAME,
NULL, /* Functions */
PHP_MINIT(getgraph),
NULL, /* MSHUTDOWN */
NULL, /* RINIT */
NULL, /* RSHUTDOWN */
NULL, /* MINFO */
#if ZEND_MODULE_API_NO >= 20010901
PHP_GETGRAPH_EXTVER,
#endif
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_GETGRAPH
extern "C" {
ZEND_GET_MODULE(getgraph)
}
#endif
| In your internal functions, you can only return zvals, not arbitrary C++ objects. In your case, you must encapsulate the Category object either in a resource or in an object (like you did for the Graph object). Either way, you cannot automatically use the C++ object's methods and properties. You must then provide functions or methods (again, like you did for the Graph object) that then should call the underlying native methods and convert their results into zvals.
edit:
OK, I assume you've already declare the Category class as a PHP class, its class entry table is in ce_category and you have this type:
struct category_object {
zend_object std;
Category *categ;
};
then:
PHP_METHOD(Graph, getCategory)
{
graph_object *obj = (graph_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
struct category_object *co;
//You ought to check whether obj is NULL and maybe throw an exception or call zend_error...
if (object_init_ex(return_value, ce_category) != SUCCESS) {
//error handling
}
co = (struct category_object *) zend_object_store_get_object(return_value TSRMLS_CC);
assert (co != NULL); //should not happen; object was just created
co->categ = retrieve_category_from_graph(obj->graph);
/* IMPORTANT NOTE: if the Category object is held by the Graph object
* (that is, it is freed when the Graph object is freed), you should either:
* - Copy the Category object, so that it is independent.
* - Increment the refcount of the PHP Graph object with
* zend_objects_store_add_ref(_by_handle). In that case, you should also store the
* handle of the PHP Graph object so that you can decrease the refcount when the
* PHP Category object is destroyed. Alternatively, you can store an IS_OBJECT
* zval and indirectly manipulate the object refcount through construction/destruction
* of the zval */
}
|
2,822,357 | 2,822,390 | How to profile my C++ application on linux | I would like to profile my c++ application on linux.
I would like to find out how much time my application spent on CPU processing vs time spent on block by IO/being idle.
I know there is a profile tool call valgrind on linux. But it breaks down time spent on each method, and it does not give me an overall picture of how much time spent on CPU processing vs idle? Or is there a way to do that with valgrind.
| I can recommend valgrind's callgrind tool in conjunction with KCacheGrind for visualization. KCacheGrind makes it pretty easy to see where the hotspots are.
Note: It's been too long since I used it, so I'm not sure if you'll be able to get I/O Wait time out of that. Perhaps in conjunction with iostat or pidstat you'll be able to see where all the time was spent.
|
2,822,487 | 2,825,959 | Template Syntax in C++ | I don't understand templates really and was trying to run a simple find the minimum for ints, doubles, chars.
First question, why is template<typename T> sometimes used, and other times template<>?
Second question, I do not know what I am doing wrong with the following code below:
#include <iostream>
template <typename T>
T minimum(T arg1, T arg2)
{
return arg1 < arg2 ? arg1 : arg2;
}
template <typename T>
// first I tried template <> instd of above, but wasn't sure the difference
T minimum<const char *>(const char *arg1, const char *arg2)
{
return strcmp(arg1, arg2) ? arg2 : arg1;
}
int main()
{
std::cout << minimum<int>(4, 2) << '\n';
std::cout << minimum<double>(2.2, -56.7) << '\n';
std::cout << minimum(2.2, 2) << '\n';
}
Compile Errors:
error C2768: 'minimum' : illegal use of explicit template arguments
error C2783: 'T minimum(const char *,const char *)' : could not deduce template argument for 'T'
: see declaration of 'minimum'
: error C2782: 'T minimum(T,T)' : template parameter 'T' is ambiguous
: see declaration of 'minimum'
Third, in getting familiar with separating .h and .cpp files, if I wanted this minimum() function to be a static function of my class, but it was the only function in that class, would I have to have a template class as well? I originally tried doing it that way instead of having it all in one file and I got some compile errors as well that I can't remember right now and was unsure how I would do that. Thanks!
| It looks like your question is almost answered, but you still have a couple of outstanding issues...
std::cout << minimum(2.2, 2) << '\n';
This won't compile with the two template functions you have provided as there is no matching function for call to minimum(double, int). This leaves you two options:
You can change your first template function to be:
template <typename T, typename U>
T minimum(T arg1, U arg2)
{
return arg1 < arg2 ? arg1 : arg2;
}
or
You can change your code to specify which specialisation to invoke:
std::cout << minimum<double>(2.2, 2) << '\n';
There is also a bug in your const char* specialisation (once the syntax error is resolved) since a zero return value from strcmp indicates that both strings are equal. The following assertion will fail:
assert(0 == strcmp("aaa", minimum("aaa", "bbb")));
This can be fixed thus:
template <>
const char* minimum<const char*>(const char* arg1, const char* arg2)
{
return strcmp(arg1, arg2) > 0 ? arg2 : arg1;
}
|
2,822,636 | 2,823,161 | call multiple c++ functions in python using threads | Suppose I have a C(++) function taking an integer, and it is bound to (C)python with python api, so I can call it from python:
import c_module
c_module.f(10)
now, I want to parallelize it. The problem is: how does the GIL work in this case? Suppose I have a queue of numbers to be processed, and some workers (threading.Thread) working in parallel, each of them calling c_module.f(number) where number is taken from a queue.
The difference with the usual case, when GIL lock the interpreter, is that now you don't need the interpreter to evaluate c_module.f because it is compiled. So the question is: in this case the processing is really parallel?
| Threads currently executing the C extension code for which the GIL was explicitly released will run in parallel. See http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock for what you need to do in your extension.
Python threads are most useful for I/O bound execution or for GUI responsiveness. I wouldn't do python-heavy execution with threads. If you want guaranteed parallelism, check out the multiprocessing library.
|
2,822,830 | 2,822,948 | How to get the Doctype Declaration in Xerces-C when using SAX2? | I am using SAX2 from Xerces-C to read an XML document. However, I would like to check the Doctype declaration (if there is any) to make sure that the XML file is in the format I am expecting.
I have tried the unparsedEntityDecl and notationDecl methods from the DTDHandler, and EntityResolver seems to be more low-level than what I am looking for.
My motivation is for this is to be able to confirm that the input is of the format I am expecting so that I can differentiate between documents which produce no output and those that are entirely of the wrong format.
| Look at LexicalHandler - startDTD will get you the Doctype.
However, it does not validate that the document actually follows that Doctype.
You need to enable validation in the reader with setFeature to do that.
( I've only used Java Xerces, but from the docs, it looks like the methods
are basically the same. )
|
2,822,915 | 2,823,966 | Odd tcp deadlock under windows | We are moving large amounts of data on a LAN and it has to happen very rapidly and reliably. Currently we use windows TCP as implemented in C++. Using large (synchronous) sends moves the data much faster than a bunch of smaller (synchronous) sends but will frequently deadlock for large gaps of time (.15 seconds) causing the overall transfer rate to plummet. This deadlock happens in very particular circumstances which makes me believe it should be preventable altogether. More importantly if we don't really know the cause we don't really know it won't happen some time with smaller sends anyway. Can anyone explain this deadlock?
Deadlock description (OK, zombie-locked, it isn't dead, but for .15 or so seconds it stops, then starts again)
The receiving side sends an ACK.
The sending side sends a packet containing the end of a message (push flag is set)
The call to socket.recv takes about .15 seconds(!) to return
About the time the call returns an ACK is sent by the receiving side
The the next packet from the sender is finally sent (why is it waiting? the tcp window is plenty big)
The odd thing about (3) is that typically that call doesn't take much time at all and receives exactly the same amount of data. On a 2Ghz machine that's 300 million instructions worth of time. I am assuming the call doesn't (heaven forbid) wait for the received data to be acked before it returns, so the ack must be waiting for the call to return, or both must be delayed by something else.
The problem NEVER happens when there is a second packet of data (part of the same message) arriving between 1 and 2. That part very clearly makes it sound like it has to do with the fact that windows TCP will not send back a no-data ACK until either a second packet arrives or a 200ms timer expires. However the delay is less than 200 ms (its more like 150 ms).
The third unseemly character (and to my mind the real culprit) is (5). Send is definitely being called well before that .15 seconds is up, but the data NEVER hits the wire before that ack returns. That is the most bizarre part of this deadlock to me. Its not a tcp blockage because the TCP window is plenty big since we set SO_RCVBUF to something like 500*1460 (which is still under a meg). The data is coming in very fast (basically there is a loop spinning out data via send) so the buffer should fill almost immediately. Msdn mentions that there various "heuristics" used in deciding when a send hits the wire, and that an already pending send + a full buffer will cause send to block until the data hits the wire (otherwise send apparently really just copies data into the tcp send buffer and returns).
Anway, why the sender doesn't actually send more data during that .15 second pause is the most bizarre part to me. The information above was captured on the receiving side via wireshark (except of course the socket.recv return times which were logged in a text file). We tried changing the send buffer to zero and turning off nagel on the sender (yes, I know nagel is about not sending small packets - but we tried turning nagel off in case that was part of the unstated "heuristics" affecting whether the message would be posted to the wire. Technically microsoft's nagel is that a small packet isn't sent if the buffer is full and there is an outstanding ACK, so it seemed like a possibility).
| The send blocking until the previous ACK is received almost certainly indicates that the TCP receive window is full (you can check this by using Wireshark to analyse the network traffic).
No matter how big your TCP window is, if the receiving application isn't processing data as fast as it's arriving then the TCP window will eventually fill up. How fast are we talking here? What is the receiving side doing with the data? (If you're writing the received data to disk then it's quite possible that your disk just can't keep up with a gigabit network at full bore).
OK, so you have a 730,000 byte receive window and you're streaming data at 480Mbps. That means it takes only 12ms to entirely fill your window - so when the 150ms delay on the receive side occurs, the receive window fills up almost instantly and causes the sender to stall.
So your root cause is this 150ms delay in scheduling your receive process. There's any number of things that could cause that (it could be as simple as the kernel needing to flush dirty pages to disk to create some more free pages for your application); you could try increasing your processes scheduling priority, but there's no guarantee that that will help.
|
2,822,965 | 2,822,983 | C++: combine const with template arguments | The following example is working when I manualy replace T wirh char *, but why is not working as it is:
template <typename T>
class A{
public:
A(const T _t) { }
};
int main(){
const char * c = "asdf";
A<char *> a(c);
}
When compiling with gcc, I get this error:
test.cpp: In function 'int main()':
test.cpp:10: error: invalid conversion from 'const char*' to 'char*'
test.cpp:10: error: initializing argument 1 of 'A<T>::A(T) [with T = char*]'
| Try converting to const T&. Also, in these cases, you should let the compiler automatically deduce the template argument, and not specify it.
|
2,822,989 | 2,823,049 | Using boost::iterator | I wrote a sparse vector class (see #1, #2.)
I would like to provide two kinds of iterators:
The first set, the regular iterators, can point any element, whether set or unset. If they are read from, they return either the set value or value_type(), if they are written to, they create the element and return the lvalue reference. Thus, they are:
Random Access Traversal Iterator and Readable and Writable Iterator
The second set, the sparse iterators, iterate over only the set elements. Since they don't need to lazily create elements that are written to, they are:
Random Access Traversal Iterator and Readable and Writable and Lvalue Iterator
I also need const versions of both, which are not writable.
I can fill in the blanks, but not sure how to use boost::iterator_adaptor to start out.
Here's what I have so far:
template<typename T>
class sparse_vector {
public:
typedef size_t size_type;
typedef T value_type;
private:
typedef T& true_reference;
typedef const T* const_pointer;
typedef sparse_vector<T> self_type;
struct ElementType {
ElementType(size_type i, T const& t): index(i), value(t) {}
ElementType(size_type i, T&& t): index(i), value(t) {}
ElementType(size_type i): index(i) {}
ElementType(ElementType const&) = default;
size_type index;
value_type value;
};
typedef vector<ElementType> array_type;
public:
typedef T* pointer;
typedef T& reference;
typedef const T& const_reference;
private:
size_type size_;
mutable typename array_type::size_type sorted_filled_;
mutable array_type data_;
// lots of code for various algorithms...
public:
class sparse_iterator
: public boost::iterator_adaptor<
sparse_iterator // Derived
, typename array_type::iterator // Base (the internal array)
, value_type // Value
, boost::random_access_traversal_tag // CategoryOrTraversal
> {...}
class iterator_proxy {
???
};
class iterator
: public boost::iterator_facade<
iterator // Derived
, ????? // Base
, ????? // Value
, boost::?????? // CategoryOrTraversal
> {
};
};
also, is this illegal?
typedef boost::reverse_iterator<sparse_iterator> reverse_sparse_iterator;
| I'm not sure that you really want to use iterator_adaptor in your case - you might want to use iterator_facade instead.
More thorough explanation: iterator_adaptors are used when you have an existing iterator (let's say std::list<int>::iterator) and want to reuse its behaviour for your iterator, eg. your iterator will return twice the value of what is in the list, but reuse traversal code from the original iterator. Or the other way around: you might want an iterator that will skip some of the elements in the original list, but return the values unchanged. I'm not sure whether you want to base your iterator (as in reuse code of) upon iterators of your underlying structures, but speaking for me, I wouldn't especially in the case of nonsparse iterator as you would probably want to create some proxy for the reference which means you can't use any underlying iterator dereference() code, and traversal is probably easy. You can, however, base your sparse_iterator on some iterator that iterates over actually existing elements of the array if you want.
There are problems with the proxy approach, so don't expect it to work flawlessly without going through many hoops. For one thing, the const version of the nonsparse iterator should still return value_type(), which means expressions like iter->foo() should translate to value_type().foo() if the corresponding entry doesn't exist. But this poses a difficulty, that pointer_proxy::operator->() should return something with operator->, preferably a pointer (definitely not value_type()). Which leads to the crucial question: A pointer to what? There are possibilities to solve this (for one, if you have your objects managed by boost::shared_pointer, you can just return a shared_pointer to a new'd instance).
For the nonsparse iterator, you need to implement:
class reference_proxy with
reference_proxy::operator& (that will probably return a pointer proxy)
reference_proxy::operator value_type&() for const uses
reference_proxy::operator const value_type&() for non-const uses
reference_proxy::foo() for any foo() member function of value_type (otherwise expressions like (*it).foo() AFAIK won't work)
class pointer_proxy with
pointer_proxy::operator* (return a reference_proxy)
pointer_proxy::operator-> (do something sensible, see above)
The parameters to the iterator facade template should be:
Reference: the reference_proxy
Pointer: the pointer_proxy
The sparse version is simpler: If the underlying iterator is sensible (ie. matches the behaviour you want) and properly implemented, you can just omit the parameters to the iterator_adaptor (except for the first two), and take all the implementation.
The "doesn't compile" problem: insert typename.
|
2,823,238 | 2,823,249 | Run-Time Binding C++ | I'm reading in my text book about virtual functions in C++ and my book doesn't elaborate on what exactly run-time binding is. It doesn't give me any information as to why I would need run-time binding.
Maybe the nice people at SO can provide me with some links or information?
Thanks :]
| How about this one? ;D
http://www.google.ca/search?hl=en&source=hp&q=virtual+function+runtime+binding+c%2B%2B&aq=f&aqi=&aql=&oq=&gs_rfai=
In all seriousness though... the first link looks decent.
Here's a preview:
The most prominent reason why a virtual function will be used is to have a different functionality in the derived class. The difference between a non-virtual member function and a virtual member function is, the non-virtual member functions are resolved at compile time.
And from another site:
In large, complex programs, virtual functions allow the programmer to simplify the programming process. If used correctly, the base class will successfully define the interface of its derived classes. However, the program will leave the implementation of this interface up to the derived classes. Therefore, the programmer can use one interface for multiple implementations. This capability also allows for the creation of class libraries, which establish standard interfaces, but allow the programmer to tailor these interfaces to any unique implementation situations that may arise. One of the most popular libraries around is the Microsoft Foundation Classes (MFC) library, which provides the interfaces necessary for programming in the Windows environment. This library frees the programmer from having to reinvent the Windows interfaces, instead allowing him or her to focus on the specific implementation of these interfaces.
|
2,823,245 | 2,823,260 | Syntax for finding structs in multisets - C++ | I can't seem to figure out the syntax for finding structs in containers.
I have a multiset of Event structs. I'm trying to find one of these structs by searching on its key. I get the compiler error commented below.
struct Event {
public:
bool operator < ( const Event & rhs ) const {
return ( time < rhs.time );
}
bool operator > ( const Event & rhs ) const {
return ( time > rhs.time );
}
bool operator == ( const Event & rhs ) const {
return ( time == rhs.time );
}
double time;
int eventID;
int hostID;
int s;
};
typedef std::multiset< Event, std::less< Event > > EventPQ;
EventPQ currentEvents;
double oldRecTime = 20.0;
EventPQ::iterator ceItr = currentEvents.find( EventPQ::key_type( oldRecTime ) ); // no matching function call
I've tried a few permutations to no avail. I thought defining the conditional equality operator was going to be enough.
Solution
After correcting my typo (sorry), I now have a solution closest to AraK's, augmented by Soapbox's suggested use of explicit:
struct Event {
explicit Event(double t) : time(t), eventID(), hostID(), s() {}
Event(double t, int eid, int hid, int stype) : time(t), eventID( eid ), hostID( hid ), s(stype) {}
...
};
EventPQ::iterator ceItr = currentEvents.find( EventPQ::key_type( Event(oldRecTime) ) );
I recently discovered that another option would have been to use find_if, discussed here.
Thanks for the help.
| You don't have a suitable constructor that accepts double. Just add the following constructor:
Event(double t) : time(t), eventID(/**/), hostIDeventID(/**/), s(/**/)
{ }
Here is how Event would look like:
struct Event {
public:
// Initialize other variables as needed
Event(double t) : time(t), eventID(/**/), hostIDeventID(/**/), s(/**/)
{ }
bool operator < ( const Event & rhs ) const {
return ( time < rhs.time );
}
bool operator > ( const Event & rhs ) const {
return ( time > rhs.time );
}
bool operator == ( const Event & rhs ) const {
return ( time == rhs.time );
}
double time;
int eventID;
int hostID;
int s;
};
// No need for std::less because it is used by default,
// when you define 'operator <' in your class
typedef std::multiset< Event > EventPQ;
EventPQ currentEvents;
double oldRecTime = 20.0;
// You can just pass the double, a temporary object will be created
// for you.
EventPQ::iterator ceItr = currentEvents.find( oldRecTime );
|
2,823,456 | 2,823,671 | Are there any tools for porting c++ code to c# code? | I have a couple c++ utilities that I would like to port over to dot net. I was wondering if there are tools for porting a c++ application to c#?
I imagine that any automated tool would make a mess of any code, so perhaps, I should also be asking if this is a good idea or not?
| The better question is why would you ever just port working code without gaining added value (ie new features)? The effort will almost cetainly be harder and take longer than you expect. Better, use the many interop capabilities of .Net to call your c++ code from C#. Focus on adding new features in C#, but don't waste your time porting working code.
|
2,823,485 | 2,824,007 | How to befriend a templated class's constructor? | Why does
class A;
template<typename T> class B
{
private:
A* a;
public:
B();
};
class A : public B<int>
{
private:
friend B<int>::B<int>();
int x;
};
template<typename T>
B<T>::B()
{
a = new A;
a->x = 5;
}
int main() { return 0; }
result in
../src/main.cpp:15: error: invalid use of constructor as a template
../src/main.cpp:15: note: use ‘B::B’ instead of ‘B::class B’ to name the constructor in a qualified name
yet changing friend B<int>::B<int>() to friend B<int>::B() results in
../src/main.cpp:15: error: no ‘void B::B()’ member function declared in class ‘B’
while removing the template completely
class A;
class B
{
private:
A* a;
public:
B();
};
class A : public B
{
private:
friend B::B();
int x;
};
B::B()
{
a = new A;
a->x = 5;
}
int main() { return 0; }
compiles and executes just fine -- despite my IDE saying friend B::B() is invalid syntax?
| Per the resolution to CWG defect 147 (the resolution was incorporated into C++03), the correct way to name a nontemplate constructor of a class template specialization is:
B<int>::B();
and not
B<int>::B<int>();
If the latter were allowed, there is an ambiguity when you have a constructor template specialization of a class template specialization: would the second <int> be for the class template or the constructor template? (see the defect report linked above for further information about that)
So, the correct way to declare the constructor of a class template specialization as a friend is:
friend B<int>::B();
Comeau 4.3.10.1 and Intel C++ 11.1 both accept that form. Neither Visual C++ 2008 nor Visual C++ 2010 accept that form, but both accept the (incorrect) form friend B<int>::B<int>(); (I will file a defect report on Microsoft Connect).
gcc does not accept either form prior to version 4.5. Bug 5023 was reported against gcc 3.0.2, but the requested resolution in the bug report was the invalid form. It appears the resolution to bug 9050 also resolves this issue and gcc 4.5 accepts the correct form. Georg Fritzsche verified this in a comment to the question.
|
2,823,700 | 2,823,817 | How can I make a child window topmost? | I have a parent form, with some child windows (not forms - just windows, for example label controls) inside it. Under certain circumstances, I want one of those child windows to be drawn "above" the others, to display a message over the entire main form.
I've tried setting HWND_TOPMOST and HWND_TOP on the child windows, but it doesn't seem to have any effect at all. Am I doing something wrong, or do HWND_TOPMOST and HWND_TOP only work on forms, as opposed to controls within forms?
Thanks.
| HWND_TOPMOST only applies to top level windows, not child windows.
Use SetWindowPos withthe HWND_TOP flag to change the target child window's zorder to put it at the top of the zorder among its siblings.
Note that zorder in child windows only applies to siblings - hwnds with the same parent.
|
2,823,713 | 2,823,727 | C++ preprocessing error in the code | #include "iostream"
#include "string"
using namespace std;
#define AA(bb) \
string(::##bb);
int main (int argc, char *argv[])
{
AA(aa);
}
This gives me a bunch of errors but I am trying to understand this error:
pre.cpp:11:1: error: pasting "::" and "aa" does not give a valid preprocessing token
Any ideas?
| :: is already a separate token, you don't need the ## token-pasting operator for the code you showed.
|
2,823,730 | 2,823,768 | Is webserver bandwith the entire HTTP Request/Response? | Just a quick question. I'm making a web application where C++ communicates with a php script over HTTP Requests/Response. The data being set back and forth is quite small ~36 bytes. But I plan to have many computers connected, contacting the server quite often. I did the math, and I could potentially have gigabytes of data transfer a month. This isn't too much of problem, but it would be if the bandwidth included the request/response headers the request size would be about ~560 bytes. That's about 16x more bandwidth than I was planning... That would be a lot. If if any one knew how hosts determine bandwidth and could share, that'd be great. Thanks.
| Assuming the web host is running Apache, You can assume the module mod_bw is being used to control the bandwidth (It's a standard). In this case requests are not part of the traffic being monitored, the only control on the requests are the amount of them, they do not count as "bandwidth" although it technically still is. The headers and frames may count though;
Although you may want to browse the documentation, doesn't seem there's much:
https://svn.apache.org/repos/asf/httpd/sandbox/mod_bw/mod_bw.txt
|
2,823,858 | 2,823,870 | Working with strings in C++ | I'm working with strings in C++. I recently came across a problem when entering strings. I'm using cin >> string; to get my string as user input. When the user enters a space into the string, the next input is automatically filled out with the remaining letters, or sometimes left blank. As the next input string is often an integer, this will result in an unpleasant bug. What's a good fix for this?
EDIT: Here's the current code:
cout << "Please print the enemy's name: ";
getline(cin, enemyName);
| You probably want to get all input into the string up until the user presses enter. In that case, it can be said that what you really want is to read a "line" of text. To do that, you'd use std::getline, like so:
std::getline(cin, enemyName);
That is assuming enemyName is defined as an std::string. If enemy name is a c-style charater array, you'd want to use cin.getline, like this:
cin.getline(enemyName, sizeof(enemyName));
But, try to avoid using C-style character arrays at all in C++.
|
2,824,014 | 2,824,025 | Explain this C++ operator definition | I have the following operator defined in a C++ class called StringProxy:
operator std::string&()
{
return m_string;
}
a) What is this and how does this work? I understand the idea of operator overloading, but they normally look like X operator+(double i).
b) Given an instance of StringProxy, how can I use this operator to get the m_string?
| This is a conversion method. To get the m_string, simply use an explicit cast: (std::string)stringProxy to perform the conversion. Depending on context (e.g. if you're assigning to a string), you may be able to do without the cast.
|
2,824,046 | 2,824,083 | Sanity Check - will a stl::Container of new'd objects each be deleted when the container itself dies? | Title pretty much covers it. If I've added say 3 objects to a list and the list goes out of scope and dies, will it call delete on each entry before going out of scope? Pretty sure yes, but getting tired and need a sanity check.
| Survey says: I'm tired and no they won't delete themeselves unless they are within some sort of container safe smart pointer in the list itself. Nap time...
|
2,824,342 | 2,824,357 | Using Tortoise SVN with C++ in Visual Studio 2008 | I have an online repository with some .h and .cpp files that make up part of a project. I'm trying to check these out and use them in a new project, but am getting errors (C4627 and C1010). All the files have been added to the project (with Add>Existing Item...), and the subdirectories that contain these files have been added to the "Additional include directories" of the project.
Would I be better off having the entire project tree in the repository? My reason for not doing so is that my colleague and I are working on different parts of the code and so want to use different main methods to test things as we go, and I didn't see any need to be passing around any compiled code etc. since I assumed that given the .h and .cpp files (with the correct settings), visual studio would be able to compile the project.
What's the best way to make Visual Studio 2008 and TortoiseSVN work well together (without spending any money)?
|
Would I be better off having the entire project tree in the repository?
Most certainly yes. You should be able to check out and build without much effort. Creating a new project every time you want to build the source and having to configure it is way too much work.
My reason for not doing so is that my colleague and I are working on different parts of the code and so want to use different main methods to test things as we go, and I didn't see any need to be passing around any compiled code etc.
Ok, just put more than one project in the solution. There's no reason you can't have separate executable projects for separate tests.
I assumed that given the .h and .cpp files (with the correct settings), visual studio would be able to compile the project.
If all of the settings are the same, then, yes, it should compile fine, but why bother with the hassle when you don't have to?
|
2,824,431 | 2,824,465 | Get the signed/unsigned variant of an integer template parameter without explicit traits | I am looking to define a template class whose template parameter will always be an integer type. The class will contain two members, one of type T, and the other as the unsigned variant of type T -- i.e. if T == int, then T_Unsigned == unsigned int. My first instinct was to do this:
template <typename T> class Range {
typedef unsigned T T_Unsigned; // does not compile
public:
Range(T min, T_Unsigned range);
private:
T m_min;
T_Unsigned m_range;
};
But it doesn't work. I then thought about using partial template specialization, like so:
template <typename T> struct UnsignedType {}; // deliberately empty
template <> struct UnsignedType<int> {
typedef unsigned int Type;
};
template <typename T> class Range {
typedef UnsignedType<T>::Type T_Unsigned;
/* ... */
};
This works, so long as you partially specialize UnsignedType for every integer type. It's a little bit of additional copy-paste work (slash judicious use of macros), but serviceable.
However, I'm now curious - is there another way of determining the signed-ness of an integer type, and/or using the unsigned variant of a type, without having to manually define a Traits class per-type? Or is this the only way to do it?
| The answer is in <type_traits>
For determining the signed-ness of a type use std::is_signed and std::is_unsigned.
For adding/removing signed-ness, there is std::make_signed and std::make_unsigned.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.