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 |
|---|---|---|---|---|
1,765,539 | 1,766,019 | Declaring function objects for comparison? | I have seen other people questions but found none that applied to what I'm trying to achieve here.
I'm trying to sort Entities via my EntityManager class using std::sort and a std::vector<Entity *>
/*Entity.h*/
class Entity
{
public:
float x,y;
};
struct compareByX{
bool operator()(const GameEntity &a, const GameEntity &b)
{
return (a.x < b.x);
}
};
/*Class EntityManager that uses Entitiy*/
typedef std::vector<Entity *> ENTITY_VECTOR; //Entity reference vector
class EntityManager: public Entity
{
private:
ENTITY_VECTOR managedEntities;
public:
void sortEntitiesX();
};
void EntityManager::sortEntitiesX()
{
/*perform sorting of the entitiesList by their X value*/
compareByX comparer;
std::sort(entityList.begin(), entityList.end(), comparer);
}
I'm getting a dozen of errors like
: error: no match for call to '(compareByX) (GameEntity* const&, GameEntity* const&)'
: note: candidates are: bool compareByX::operator()(const GameEntity&, const GameEntity&)
I'm not sure but ENTITY_VECTOR is std::vector<Entity *> , and I don't know if that could be the problem when using the compareByX function object ?
I'm pretty new to C++, so any kind of help is welcome.
| And a third one comes in... After you edited you question, still one open topic: your comparator takes a const & to the GameEntity class. It should, in order to work with the values of the vector<GameEntity*>, take const GameEntity* arguments instead.
|
1,765,558 | 1,765,570 | C++ String manipulation - if stament | I have the following code that works correctly. However after I add an else statement anything always evaluates to else
wgetstr(inputWin, ch); //get line and store in ch variable
str = ch; //make input from char* to string
if(str=="m" || str=="M"){
showFeedback("Data Memory Updated");
}
if(str=="p" || str=="P"){
showFeedback("Program Memory Updated");
}
if(str=="g" || str=="G"){
showFeedback("Accumulator, Program Counter, Zero Result Updated");
}
if(str=="e" || str=="E"){
showFeedback("Editing Mode Enabled");
}
if(str=="c" || str=="C"){
showFeedback("Program Copied Into Program Memory");
}
if(str=="r" || str=="R"){
showFeedback("Executing Program");
}
if(str=="x" || str=="X"){
showFeedback("Program Exited");
}
All the previous evaluates correctly based on what the input is. i.e If I enter "m" it calls the showeFeedback("Data Memory Updated") on so on, but if I add the following else statement, I always get "Invalid Command Entered" no matter what I enter.
else{
showFeedback("Invalid Command Entered");
}
| All of those are separate if-statements. The else you added only goes with the last one. Change all but the first if to else if and it should work like you expect.
|
1,765,776 | 1,777,284 | Soundflower input applications | I've downloaded the source of Soundflower and I am trying to retrieve a list of all applications currently sending data to Soundflower.
I'd like to manipulate each application's sound separately just like JACK and Audio Hijack does.
Any ideas?
| Unfortunately, this isn't something you're going to be able to find out from within the Soundflower kext because applications don't connect directly to audio drivers. The Audio HAL is an audio driver's user client and manages audio input and output between apps and the kernel.
You should look into using a HAL Plug-in. Your plug-in code will get loaded by any application that uses Core Audio and you can do whatever you need to do from there and use some IPC to communicate with your driver and app.
|
1,766,014 | 1,768,042 | Are double* and double** blittable types? C# | I have a question regarding marshalling of C++ arrays to C#.
Does the double* automatically convert to double[]?
I know double is a blittable type, so double from C++ is the same as double from C#.
And what about double**, does it convert to double[,] ?
I have the following unmanaged function:
int get_values(double** param,int sz)
where param is a pointer to array of doubles and sz it's size.
How can I DLLImport this function to C#?
Thanks in advance
| The declaration makes no sense. It would make sense if the function takes a pointer to an array of doubles, but then the declaration would be
int get_values(double* array, int size);
Where size would give the size of the array allocated by the client and the function's return value indicates how many doubles were actually copied into the array. The equivalent P/Invoke declaration would be:
[DllImport("blah.dll")]
private static extern int get_values(double[] array, int size);
You have to allocate the array with new to the size you promised before calling the function.
But the double** argument is a hangup. It could mean that the function returns a pointer to an array of doubles but then the size argument makes little sense. Since it is the function that owns the array and controls its size. Or it could mean that the client passes a two-dimensional array, but then having only one size argument makes no sense.
Please update your question with the correct interpretation of what the function does.
|
1,766,134 | 1,766,161 | array reallocation C++ | Suppose you have an array, items, with capacity 5 and suppose also you have a count varaible that counts each entry added to the array. How would you realloacte the array? Using C++ syntax?
void BST::reallocate()
{
item *new_array = new item[size*2];
for ( int array_index = 0; array_index < size * 2; array_index++ )
{
if ( ! items[array_index].empty )
{
new_array[array_index].theData = items[array_index].theData;
new_array[array_index].empty = false;
}
}
maxSize += size;
delete [] items;
items = NULL;
items = new_array;
}
How do you reallocate an array?
BST ctor is below with the private items struct, just to eliminate any confusion.
BST::BST(int capacity) : items(new item[capacity]), Position(0),
leftChild(0), rightChild(0), maxSize(capacity)
{
}
this is in the BST header:
private:
int size;
int maxSize;
int Position;
int leftChild;
int rightChild;
struct item
{
bool empty;
data theData;
};
item *items;
The quesetion is that i seem to be having a hard time with the reallocation of my items array.
| Your old array items has only size elements, so you need to change the upper limit in your for loop to size from size*2 when you're copying the old elements to the new array.
|
1,766,150 | 1,766,164 | C++ convert int and string to char* | This is a little hard I can't figure it out.
I have an int and a string that I need to store it as a char*, the int must be in hex
i.e.
int a = 31;
string str = "a number";
I need to put both separate by a tab into a char*.
Output should be like this:
1F a number
| With appropriate includes:
#include <sstream>
#include <ostream>
#include <iomanip>
Something like this:
std::ostringstream oss;
oss << std::hex << a << '\t' << str << '\n';
Copy the result from:
oss.str().c_str()
Note that the result of c_str is a temporary(!) const char* so if your function takes char * you will need to allocate a mutable copy somewhere. (Perhaps copy it to a std::vector<char>.)
|
1,766,275 | 1,767,356 | How to obtain the PIDL of an IShellFolder | If I have an IShellFolder interface pointer. How might I obtain its PIDL?
I can see how to enumerate its children, and I can see how to use it to compare any two children. But how might I get its own pidl?
I ask because I'd like to know:
Is this IShellFolder == Another IShellFolder
I can use IShellFolder::CompareIDs(), but I have to have the IDs of both folders.
| I found that you can query an IShellFolder for its IPersistFolder2, which has GetCurFolder(), which returns its absolute PIDL. I could then simply use the IShellFolder for the desktop to CompareIDs() to determine if they're equal. I found the outlines of this while looking at SHGetIDListFromObject. I couldn't just use that function, because its Vista, and I need XP compatibility.
Here's a sketch of how it works (assuming you have an ifolder_desktop, and ifolder_other, which are IShellFolder pointers. Pidl is a simple helper that ensures that the IDLISTs are deallocated properly):
CComQIPtr<IPersistFolder2> ipf2_desktop(ifolder_desktop);
CComQIPtr<IPersistFolder2> ipf2_folder(ifolder_other);
Pidl pidl_desktop, pidl_folder;
VERIFY(SUCCEEDED(ipf2_desktop->GetCurFolder(pidl_desktop)));
VERIFY(SUCCEEDED(ipf2_folder->GetCurFolder(pidl_folder)));
HRESULT hr = ifolder_desktop->CompareIDs(NULL, pidl_desktop, pidl_folder);
pCmdUI->Enable(SUCCEEDED(hr) && HRESULT_CODE(hr) != 0);
In case anyone is interested in my simple Pidl class:
class Pidl
{
public:
// create empty
Pidl() : m_pidl(NULL) { }
// create one of specified size
explicit Pidl(size_t size) : m_pidl(Pidl_Create(size)) {}
// create a copy of a given PIDL
explicit Pidl(const ITEMIDLIST * pidl) : m_pidl(Pidl_Copy(pidl)) {}
// create an absolute PIDL from a parent + child
Pidl(const ITEMIDLIST_ABSOLUTE * pParent, const ITEMIDLIST_RELATIVE * pChild) : m_pidl(Pidl_Concatenate(pParent, pChild)) { }
// return our PIDL for general use (but retain ownership of it)
operator const ITEMIDLIST * () { return m_pidl; }
// return a pointer to our pointer, for use in functions that assign to a PIDL
operator ITEMIDLIST ** ()
{
free();
return &m_pidl;
}
// release ownership of our PIDL
ITEMIDLIST * release()
{
ITEMIDLIST * pidl = m_pidl;
m_pidl = NULL;
return pidl;
}
void free()
{
if (m_pidl)
//Pidl_Free(m_pidl);
ILFree(m_pidl);
}
// automatically free our pidl (if we have one)
~Pidl()
{
free();
}
private:
ITEMIDLIST * m_pidl;
};
|
1,766,351 | 1,766,547 | Causing push_back in vector<int> to segmentaion fault on what seems to be simple operation | I'm working on a program for Project Euler to add all the digits of 2^1000. So far I've been able to track the program segmentation faults when it reaches around 5 digits and tries to push a one onto the vector at line 61 in the function carry().
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class MegaNumber
{
vector<int> data; //carries an array of numbers under ten, would be char but for simplicity's sake
void multiplyAssign(int operand, int index); //the recursive function called by the *= operator
void carry(int index);//if one of the data entries becomes more than ten call this function
public:
void printNumber(); //does what it says on the can
void operator*=(MegaNumber operand);
void operator*=(int operand);
void operator+=(int operand);
MegaNumber(string);
unsigned long int AddAllDigits();//returns the value of all of the digits summed
};
MegaNumber::MegaNumber(string operand)
{
for(int i= operand.size()-1; i>=0;i--) //run it into the memory smallest digit first
{
data.push_back(operand[i]-48); //converts a text char to an int
}
}
void MegaNumber::printNumber()
{
int temp = data.size();
for(unsigned int i=(temp); i>0;--i)
{
cout << (int)data[i-1];
}
}
void MegaNumber::operator*=(int operand)
{
if(operand > 9)
{
cout << "function does not yet deal with large ints than 9";
}
else multiplyAssign(operand, 0);
}
void MegaNumber::multiplyAssign(int operand, int index)
{
data[index] *=operand;
if(index<data.size()) multiplyAssign(operand, index+1);
if(data[index] > 9) carry(index);
}
void MegaNumber::carry(int index)
{
int temp = (data[index] / 10); //calculate the amount to carry
if(data.size()==index+1)
{
data.push_back(temp);//if there is no upper digit push it onto the stack
}
else
{
data[index+1]+=temp; //else add it to the next digit
if(data[index+1]>9) carry(index+1); //rinse and repeat
}
data[index]-=temp*10; //remove what's been carried
}
unsigned long int MegaNumber::AddAllDigits() //does what it says on the can
{
unsigned long int Dagger = 0;
for(int i=0; i<data.size();i++) Dagger+=data[i];
return Dagger;
}
int main()
{
MegaNumber A("2");
A.printNumber();
cout << "\n";
for(unsigned int i=0; i<20; i++) A*=2;
A.printNumber();
cout << "\n";
cout << A.AddAllDigits() << "\n";
cout << "Hello world!" << endl;
return 0;
}
What may be causing this?
| void MegaNumber::multiplyAssign(int operand, int index)
{
data[index] *=operand;
if(index<data.size()) multiplyAssign(operand, index+1);
if(data[index] > 9) carry(index);
}
index is 0 based, while data.size() is 1 based so to say, meaning data.size() returns number 1 greater than the largest valid index.
So looks like you intention was
if( index < data.size() - 1) multiplyAssign(operand, index+1);
Then it works.
P.S. break your code into lines, whoever has to maintain your code will thank you for that:
if (index < data.size() - 1)
{
multiplyAssign(operand, index + 1);
}
|
1,766,711 | 1,766,764 | Enum declaration inside a scope that is a parameter of a macro | I am trying to create a macro that takes a scope as a parameter.
I know, it is probably not a good thing etc etc.
I was trying this and got the problem that preprocessor looks for commas and parentheses... the problem is with enum.
How would I declare a enum inside a scope that is a parameter of a macro?
when the compiler see the comma between enum itens, it takes it as a separator.
If you are curious to know why I entered into this, is because I need to register my namespaces and classes, for namespaces I need to know when they are closed, so I was thinking to create a macro that initially calls a static function that register the namespace, encapsulate its contents and finally call a static function that removes the namespace from the registry.
With a macro it would be easier for the coder to do this and make sure he doesn't forget to remove the namespace in the end of the bracket.
Thanks,
Joe
EDIT:
I want a macro that accepts a scope as parameters:
#define MYMACRO(unkownscope) unknownscope
class MYMACRO({
// please, don't take this code seriously, it is just an example so you can understand my question
});
now, if I try:
#define MYMACRO(unkownscope) unknownscope
class MYMACRO({
enum {
anything = 1,
everything = 2
};
});
it won't compile because of the comma inside the enum, because the compiler thinks it is a separator of the macro. It doesn't happen with commas inside parentheses, example:
int a(){
int x = anyfunction(1, 2);
}
would compile normally because the comma is inside a double parentheses.
Sorry for not being able to explain earlier... my english is not that good and the words just keep skipping me =[
Ty for the answers!
Joe
| It sounds like you are pushing the preprocessor beyond where it's willing to go. While it's not as elegant, how about breaking your macro in two (one pre- and one post-) and rather then passing a "scope" as parameter, you surround your scope with you pre- and post- macros.
So, if your macro looks something like:
SOMACRO({ ... });
You would instead do something like:
PRESOMACRO();
{ ... };
POSTSOMACRO();
|
1,766,743 | 1,766,884 | wxWidgets and "Implement_App" causes _main duplicate symbol error | I'm compiling a trivial wxWidgets app on MacOS X 10.6 with XCode 3.2
The linker is return an error about the symbol _main being defined twice:
once in main.mm
once in the test_app.cpp file.
After I commented out the macro:
Implement_App(TestApp)
The error went away, compiled & linked and I was able to run the application.
I haven't found this anywhere so any ideas about this?
| IMPLEMENT_APP is a macro used in wxWidgets to create an entry point to the program without worrying about whether the program will be compiled on Windows, Mac, *nix, or whatever. As a result of this, IMPLEMENT_APP has to define main (or its equivalent, such as WinMain).
You might find the IMPLEMENT_APP_NO_MAIN macro to be useful. Check the other IMPLEMENT_APP_XXX functions in wx/app.h, too.
This paragraph from the wxApp overview is a little helpful too:
Note the use of IMPLEMENT_APP(appClass), which allows wxWidgets to dynamically create an instance of the application object at the appropriate point in wxWidgets initialization. Previous versions of wxWidgets used to rely on the creation of a global application object, but this is no longer recommended, because required global initialization may not have been performed at application object construction time.
|
1,767,449 | 1,767,471 | C++ HTTP / HTML Socket Question | I'm building an application which I'd like to have it connect to a website and parse some data off it. I'm wondering if anyone could provide me some raw example code.
I don't necessarily need help parsing, I'm just wondering in C++ how would I go about downloading the data from the page into my app so that I can start parsing the data I need out of it?
| Check out boost.asio [examples].
|
1,767,458 | 1,767,514 | Modeling "optional" inheritance | I'm having trouble deciding on a way to model this type of relationship...
All bosses can do certain things and have certain things (velocities, health, etc.) so these are part of the "main" abstract boss class.
class Boss // An abstract base class
{
//Stuff that all Bosses can do/have and pure virtual functions
};
Now I want to specify a few more pure virtual functions and members for bosses that can shoot. I'm wondering how I should model this? I've considered deriving a ShootingBoss Class from the Boss class, but specific bosses are classes in themselves (with Boss just being an abstract base class that they are derived from.) Thus if ShootingBoss is derived from Boss, and a specific boss derives from ShootingBoss, that boss won't be able to access the protected data in the Boss class.
Boss(ABC) -> ShootingBoss(ABC) -> SomeSpecificBoss(can't access protected data from Boss?)
Basically, I'm wondering what the recommended way to model this is. Any help is appreciated. If more information is needed, I'd be happy to offer.
| I think you need to look into Mixin classes.
For example, you could create the following classes:
class Boss {
// Here you will include all (pure virtual) methods which are common
// to all bosses, and all bosses MUST implement.
};
class Shooter {
// This is a mixin class which defines shooting capabilities
// Here you will include all (pure virtual) methods which are common
// to all shooters, and all shooters MUST implement.
};
class ShootingBoss : public Boss, public Shooter
{
// A boss who shoots!
// This is where you implement the correct behaviour.
};
Mixins require multiple inheritance to be used, and there are many pitfalls and complexities to doing so. I suggest you look at answers to questions like this one to ensure that you avoid these pitfalls.
|
1,767,479 | 1,767,544 | WriteFile function "freezes" | I'm trying rewrite xCmd which can start a process on a remote machine. Basically it installs itself as a service on the target computer and then starts the requested process. Everything is working fine, but i noticed an error. xCmd is communicating through pipes, and it uses WriteFile(). My problem is, that if i run my API (or the originally, both produce this error), then for the first time it will start the requested process, but if i start it one more time, then it will "freeze out" at this line:
WriteFile( hCommandPipe, &msg, sizeof(msg), &dwTemp, NULL );
WriteFile didn't returns any errorcode, the program just stops here. I can't even close cmd window. I can only close this, when i close on the target computer the service.
Can anyone help me to solve this? It's really annoying and i have no idea :(
Here is the function which isn't working properly:
BOOL ExecuteRemoteCommand()
{
DWORD dwTemp = 0;
xCmdMessage msg;
xCmdResponse response;
::ZeroMemory( &msg, sizeof(msg) );
::ZeroMemory( &response, sizeof(response) );
FillMessage( &msg );
// Send message to service
WriteFile( hCommandPipe, &msg, sizeof(msg), &dwTemp, NULL );
// Connects to remote pipes (stdout, stdin, stderr)
if ( ConnectToRemotePipes( 5, 1000 ) )
{
StdOutput( _T("Ok\n\n") );
// Waiting for response from service
ReadFile( hCommandPipe, &response, sizeof(response), &dwTemp, NULL );
}
else
StdOutput( _T("Failed\n\n") );
if ( response.dwErrorCode == 0 )
_tprintf( _T("\nRemote command returned %d(0x%X)\n"),
response.dwReturnCode,
response.dwReturnCode );
else
_tprintf( _T("\nRemote command failed to start. Returned error code is %d(0x%X)\n"),
response.dwErrorCode,
response.dwErrorCode );
return TRUE;
}
Thanks in advance!
kampi
| I think that means that the other end of the pipe connection is not reading data out of the pipe and the pipe buffer is full.
It may also indicate that the other end has closed their pipe handle. For anonymous pipes that would cause an error when you try to write, but I don't remember if that's also true with named pipes.
If the pipe buffer is full when an application uses the WriteFile function to write to a pipe, the write operation may not finish immediately. The write operation will be completed when a read operation (using the ReadFile function) makes more system buffer space available for the pipe.
MSDN
The write operation will block until the data is read from the pipe so that the additional buffer quota can be released.
MSDN
|
1,767,670 | 1,767,691 | Is it possible to stack Yacc grammar rule code? | Lets say I need to run some initialization code everytime I match a rule how can I reduce the redundancy?
rule : TOKEN1 { init(); token1Code(); }
| TOKEN2 { init(); token2Code(); }
;
Also is it possible to do something like
rule : TOKEN1
| TOKEN2
{ codeForToken1OrToken2(); }
;
| You can use something like:
rule : { init(); } real_rule { codeForToken1or2(); } ;
real_rule : TOKEN1 { token1Code(); }
| TOKEN2 { token2Code(); }
;
But this may introduce conflicts, depending on how 'rule' is used.
|
1,767,679 | 1,769,296 | Incomplete Type memory leaks? | Microsoft Visual Studio 2008 is giving me the following warning:
warning C4150: deletion of pointer to incomplete type 'GLCM::Component'; no destructor called
This is probably because I have defined Handles to forward declared types in several places, so now the Handle class is claiming it won't call the destructor on the given object.
I have VLD running and I'm not seeing any leaks. Is this literally not calling the destructor for this object or is this a "may not call destructor for object" warning?
Yet another memory leak question from me, haha.
| It often happen when using Pimpl, so I'll focus on the solution there:
class FooImpl;
class Foo
{
public:
// stuff
private:
Pimpl<FooImpl> m_impl;
};
The problem here is that unless you declare a destructor, it will be automatically generated, inline, by the compiler. But of course, the compiler will have no idea of the complete type of FooImpl there.
You thus have to explicitly define the destructor, even if empty, and put the definition somewhere where the complete type of FooImpl is visible.
// cpp file
class FooImpl
{
};
Foo::~Foo() {} // Empty, but now correctly generated
// because FooImpl complete at this point.
Also, if like me you defined your Pimpl class to be pretty smart (regarding construction, copy and assignment), then those will also need to be defined in the .cpp file.
It's really a hassle, but then you have nicely encapsulated your implementation details, so I suppose it's worth it.
|
1,767,919 | 1,767,937 | std vector + default allocator + direct array access? | If I create a std::vector with the default allocator like this:
vector<int> myVec = vector<int>();
myVec.push_back(3);
myVec.push_back(5);
myVec.push_back(8);
Does the vector then store the actual data internally into an array of int? Is it possible to get a pointer to this array and iterate directly over it using this pointer?
| Yes, vector is designed so you can do this, use &myVec[0] to get an int*. You can also use vector's iterator type, which behaves similarly. (Pointers are valid random-access iterators.) That you're using the default allocator, or any other allocator, doesn't change any of this, it's a required part of vector's interface.
Vectors are guaranteed to use contiguous storage. In particular from those many results, check this one from Stroustrup himself.
|
1,768,075 | 1,768,100 | Is it a good idea to put all project headers into one file HEADERS.h? | I talked to my instructor the other day and asked him this question. He told me that I could go for smaller projects, but I'm starting a chess program and I was wondering what Stack Overflow thinks about this issue. Should I include all headers into one file, or separate them?
| Normally, you want separate headers.
Including more than necessary does a few potentially bad things.
This is single greatest cause of slow compile times. Unnecessary inclusion of extra headers slows down compilation, since each source file has to worry about more info than it needs. It starts as a small problem, and before you know it hundreds of developers are wasting dozens to hundreds of hours each because the problem got too far out of hand to fix. Even though you're working on small problems, it's important to understand proper separation of headers - it's easy to get right the first time but very hard to fix later if you ignore it.
You lose the ability (depending on compiler/IDE) to correctly handle dependencies, and wind up building more information than you need to build.
You lose maintainability. It's more difficult to maintain software when you have large, single files, than when you have lots of small, concise files.
You make the code more difficult to understand, hence more prone to bugs. By having everything in one file, it's easier to get "lost" in the huge header.
|
1,768,294 | 1,768,382 | How to allocate a 2D array of pointers in C++ | I'm trying to make a pointer point to a 2D array of pointers. What is the syntax and how would I access elements?
| By the letter of the law, here's how to do it:
// Create 2D array of pointers:
int*** array2d = new (int**)[rows];
for (int i = 0; i < rows; ++i) {
array2d[i] = new (int*)[cols];
}
// Null out the pointers contained in the array:
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
array2d[i][j] = NULL;
}
}
Be careful to delete the contained pointers, the row arrays, and the column array all separately and in the correct order.
However, more frequently in C++ you'd create a class that internally managed a 1D array of pointers and overload the function call operator to provide 2D indexing. That way you're really have a contiguous array of pointers, rather than an array of arrays of pointers.
|
1,768,477 | 1,768,492 | Finding bugs in Subversion's mixed revision working copies | The project I work on has recently been switched from a horribly antiquated revision control system to Subversion. I felt like I had a fairly good understanding of Subversion a few years ago, but once I learned about Mercurial, I forgot about Subversion quickly.
My question is targeted at those who work with a sizable number (15+) developers on the same branch in Subversion.
Let's say you checkout rev N of the repository. You make some changes and then commit. Meanwhile, other developers have made changes to other files. You hear about another developers changes to subsystem X and decide you need them immediately. You don't want to update the entire working copy because it would pull in all sorts of stuff and then you would have to do a lengthy compile (C++ project). The risk I see is that the developer updates only subsystem X not realizing that the new code depends on a recent change in subsystem Y. The code compiles, but crashes at runtime.
How do you deal with this?
Does the developer report what they think might be a bug (even though it's not a bug)?
Do you require developers to update their entire working copy before reporting a bug? Wouldn't this deter bug reports?
Do you prevent this situation from occurring through some mechanism I haven't thought of?
| Since you committed all your work in progress, you have no reason not to update your copy with the entire latest revision. The lengthy compile is part of the price of a large project. The compile time is almost always less than the time spent trying to determine whether you have a bug, or whether there's some obscure incompatibility because you didn't check everything out.
That project had distributed compiles to all the workstations in the group. Since we had about 15 computers for the task, that meant what would normally be a 6 hour or so build took about 25 minutes.
|
1,768,651 | 1,809,209 | SMART ASSERT for C++ application? | Is it good to define a new macro that craters my need of showing failed assertion to user and with just enough information for developers to debug the issue.
Message for user, what the
user should do with this message at last information for the developer
#define ASSERT(f) \
do \
{ \
if (!(f) && AfxAssertFailedLine(THIS_FILE, __LINE__)) \
AfxDebugBreak(); \
} while (0) \
sample message fn that we use,
MessageBox(_T("Error in finding file."),_T("TITLE"),MB_ICONERROR);
| There's a couple things I would consider from the end-user's standpoint.
Who is the target audience? If your grandmother is using this program, would these assertion messageboxes accomplish anything beyond frustrating her?
How frequently would these assertions fail? One assertion during a week of normal usage would certainly justify keeping it in the program, but several an hour would just irritate the user. The middle ground is obviously very difficult to gauge.
Have you considered putting in an "Enable Assertions" preference into the program? That way, if there are some more technical-minded (and helpful) users, they can explicitly enable the assertions and inform you when things go wrong; and if some users have no idea what an assertion is or why they are getting popups in your program, they can just disable the assertions and continue to happily use your program. Hopefully, you can put a "Do not show me assertion failure messages anymore" checkbox on the popup.
I'd say that forcing the assertion popups on users would be a plain bad idea, but allowing them to enable or disable the warnings would be a good approach.
|
1,768,834 | 1,768,923 | Determine Parent Class from boost::any | May I know is there any way to determine parent class from boost::any?
#include <iostream>
#include <boost/any.hpp>
class a {
public:
virtual ~a() {}
};
class b : public a {
};
bool is_class_a(const boost::any& any)
{
return boost::any_cast<a>(&any) != 0;
}
bool is_class_a_v2(const boost::any& any)
{
try
{
boost::any_cast<a>(any);
return true;
}
catch(const boost::bad_any_cast &)
{
return false;
}
}
int main()
{
std::cout<< is_class_a(b())<< std::endl; // return 0. but i wish to return 1.
std::cout<< is_class_a(a())<< std::endl; // return 1.
std::cout<< is_class_a_v2(b())<< std::endl; // return 0. but i wish to return 1.
std::cout<< is_class_a_v2(a())<< std::endl; // return 1.
}
| boost::any was designed so that it holds strongly informational objects for which identity is not significant. If you want to work with polymorphic types then you could use pointers to base class or boost::shared_ptr with base class instead of boost::any.
|
1,768,991 | 1,769,417 | Cross platform unicode path handling | I'm using boost::filesystem for cross-platform path manipulation, but this breaks down when calls need to be made down into interfaces I don't control that won't accept UTF-8. For example when using the Windows API, I need to convert to UTF-16, and then call the wide-string version of whatever function I was about to call, and then convert any output back to UTF-8.
While the wpath, and other w* forms of many of the boost::filesystem functions help keep sanity, are there any suggestions for how best to handle this conversion to wide-string forms where needed, while maintaining consistency in my own code?
| Well the simplest way would be to make some kind of generic routine that would return string encoded the way you'd want for provided path or a wrapper class around the path.
boost::filesystem::wpath boostPath( L"c:\\some_path" );
MyPathWrapper p( boostPath );
std::wstring sUtf8 = p.file_string_utf8();
std::wstring sUtf16 = p.file_string_utf16();
// or
std::wstring sUtf8 = p.file_string( CP_UTF8 );
// ...
Something like that.
|
1,769,023 | 1,783,458 | Is there any regular expression engine that does Just-In-Time compiling? | My Questions is
Is there any regular expression engine that does Just-In-Time compiling during regex pattern parsing and use when matching / replacing the texts? Or where can I learn JIT for i386 or x64 architecture?
Why I need it
I was recently trying to benchmark Python’s built-in regex engine compared with normal C code with around 10MB of data.
I found that for a straightforward replacing (for example ab to zzz) it’s relatively fast: just 2 to 3 times slower than C.
But for [a-z]c it took around 5 to 8 times as much time as C.
And with grouping (e.g. ([a-z])(c) to AA\2\1BB ) it took 20 to 40 times as much time as C.
It’s not Just-In-Time compiling yet, but I think, if I could do Just-In-Time compiling, It could speed up a lot more.
PS: I use profiling for each regex pattern during compiling patterns,
for example, profile 1 for simple one like ab, profile 2 for range [a-z]c, profile 3 with grouping ([a-z])(c), each profile has separate codes, so no extra cost needed when matching and replacing simple patterns.
Update 1
I have tried it with psyco, and it doesn’t improve the speed that much.
May be because I am doing text replacing against big data, not looping many times.
If I am not wrong, Python’s re.sub is running it natively already I think, so pysco cannot improve the speed that much.
Update 2
I have tried with boost regex wrapped into python, but it’s even slower than Python’s regex, so it seems like the bottleneck is in Python’s string processing and Jan Goyvaerts has also pointed me to that in the answer.
Update
I’d like to convert regex pattern ab[a-z]c to machine code, like the following equivalent C code (*s points to 10MB long texts):
do{
if(*s=='a' && s[1]=='b' && s[2]>='a' && s[2]<='z' && s[3]=='c') return 1;
}while(*s++);
return 0;
Any ideas?
| The only regex engine that I know that can compile regular expressions into executable code is the one in .NET when you pass RegexOptions.Compiled. That causes the Regex class to emit MSIL which can then be JITted like any other .NET code.
Whether than makes the .NET regex engine faster than others is a totally different matter. When searching and replacing using relatively simple regular expressions on large data sets, string handling becomes far more important. .NET strings are immutable, so much will depend on how many times the string needs to be reallocated.
Hand-coding the operation will always be faster, because the code isn't equivalent. The regex code maintains certain information about the regex match and the capturing groups which your code does not. In most situations, the extra time you spend hand-coding the search-and-replace instead of using a regex isn't worth the effort, particularly if you factor in that switching to a different regex is trivial when your requirements change, while rewriting the search-and-replace using procedural code takes much more time.
In my experience, PCRE is one of the fastest regex engines around. It doesn't include a ready-made search-and-replace, however.
|
1,769,350 | 1,770,325 | IO Completion ports: How does WSARecv() work? | I want to write a server using a pool of worker threads and an IO completion port. The server should processes and forwards messages between multiple clients. The 'per client' data is in a class ClientContext. Data between instances of this class are exchanged using the worker threads. I think this is a typical scenario.
However, I have two problems with those IO completion ports.
(1) The first problem is that the server basically receives data from clients but I never know if a complete message was received. In fact WSAGetLastError() always returns that WSARecv() is still pending. I tried to wait for the event OVERLAPPED.hEvent with WaitForMultipleObjects(). However, it blocks forever, i.e WSARecv() never completes in my program.
My goal is to be absolutely sure that the whole message has been received before further processing starts. My message has a 'message length' field in its header, but I don't really see how to use it with the IOCP function parameters.
(2) If WSARecv() is commented out in the code snippet below, the program still receives data. What does that mean? Does it mean that I don't need to call WSARecv() at all? I am not able to get a deterministic behaviour with those IO completion ports.
Thanks for your help!
while(WaitForSingleObject(module_com->m_shutdown_event, 0)!= WAIT_OBJECT_0)
{
dequeue_result = GetQueuedCompletionStatus(module_com->m_h_io_completion_port,
&transfered_bytes,
(LPDWORD)&lp_completion_key,
&p_ol,
INFINITE);
if (lp_completion_key == NULL)
{
//Shutting down
break;
}
//Get client context
current_context = (ClientContext *)lp_completion_key;
//IOCP error
if(dequeue_result == FALSE)
{
//... do some error handling...
}
else
{
// 'per client' data
thread_state = current_context->GetState();
wsa_recv_buf = current_context->GetWSABUFPtr();
// 'per call' data
this_overlapped = current_context->GetOVERLAPPEDPtr();
}
while(thread_state != STATE_DONE)
{
switch(thread_state)
{
case STATE_INIT:
//Check if completion packet has been posted by internal function or by WSARecv(), WSASend()
if(transfered_bytes > 0)
{
dwFlags = 0;
transf_now = 0;
transf_result = WSARecv(current_context->GetSocket(),
wsa_recv_buf,
1,
&transf_now,
&dwFlags,
this_overlapped,
NULL);
if (SOCKET_ERROR == transf_result && WSAGetLastError() != WSA_IO_PENDING)
{
//...error handling...
break;
}
// put received message into a message queue
}
else // (transfered_bytes == 0)
{
// Another context passed data to this context
// and notified it via PostQueuedCompletionStatus().
}
break;
}
}
}
|
(1) The first problem is that the
server basically receives data from
clients but I never know if a complete
message was received.
Your recv calls can return anywhere from 1 byte to the whole 'message'. You need to include logic that works out when it has enough data to work out the length of the complete 'message' and then work out when you actually have a complete 'message'. Whilst you do NOT have enough data you can reissue a recv call using the same memory buffer but with an updated WSABUF structure that points to the end of the data that you have already recvd. In that way you can accumulate a full message in your buffer without needing to copy data after every recv call completes.
(2) If WSARecv() is commented out in
the code snippet below, the program
still receives data. What does that
mean? Does it mean that I don't need
to call WSARecv() at all?
I expect it just means you have a bug in your code...
Note that it's 'better' from a scalability point of view not to use the event in the overlapped structure and instead to associate the socket with the IOCP and allow the completions to be posted to a thread pool that deals with your completions.
I have a free IOCP client/server framework available from here which may give you some hints; and a series of articles on CodeProject (first one is here: http://www.codeproject.com/KB/IP/jbsocketserver1.aspx) where I deal with the whole 'reading complete messages' problem (see "Chunking the byte stream").
|
1,769,627 | 1,769,642 | concept question about dll | My boss asks me to create a dll file using C++. The dll file needs to do the following:
create a blank area in Window
create some simple shapes (for an
example, a rectangle) on the blank
area
control the locations of the shapes
in the blank area
I am new to C++, so please correct me if my understand is incorrect
Dll is a binary file, does it allow to call other libraries to create the blank area?
| the DLL should be called from some executable and the dll can also call other dll's functions. While creating a dll, you need to create an executable to test the dll, and you can use other dll by dynamically loading or using its .lib in the project.
|
1,769,731 | 1,770,899 | How to set auto=repeat on a qaction in a qtoolbar? | I'd like to use the autorepeat feature of the QToolButton class.
The problem is that the instances are created automatically when using QToolBar::addAction() and I can't find a way to reach them: QToolBar::widgetForAction() doesn't seem to work in that case (always returns NULL).
Any ideas?
Thanks
| There seem to be no simple way. The best I found is to use QObject::findChldren :
foreach(QToolButton* pButton, pToolBar->findChildren<QToolButton*>()) {
if (pButton->defaultAction() == pTheActionIWant) {
...
}
}
|
1,770,081 | 1,770,154 | Initialising arrays in C++ | Everywhere I look there are people who argue vociferously that uninitialised variables are bad and I certainly agree and understand why - however; my question is, are there occasions when you would not want to do this?
For example, take the code:
char arrBuffer[1024] = { '\0' };
Does NULLing the entire array create a performance impact over using the array without initialising it?
| I assume a stack initialization because static arrays are auto-initialized.
G++ output
char whatever[2567] = {'\0'};
8048530: 8d 95 f5 f5 ff ff lea -0xa0b(%ebp),%edx
8048536: b8 07 0a 00 00 mov $0xa07,%eax
804853b: 89 44 24 08 mov %eax,0x8(%esp)
804853f: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
8048546: 00
8048547: 89 14 24 mov %edx,(%esp)
804854a: e8 b9 fe ff ff call 8048408 <memset@plt>
So, you initialize with {'\0'} and a call to memset is done, so yes, you have a performance hit.
|
1,770,090 | 1,770,175 | What C++ tutorial would you recommend for an experienced programmer that has some patchy knowledge about the language? | In my early days of programming, before I started working professionally, I wrote a fair share of trinket/exercise apps in C++ and felt fairly confident that I know the language. Then, as opportunity came, I went to do real work and left the C/C++ world. For the past 5 years I've written tons of code in C# and have had scarcely any encounters with the C/C++ languages. Now, after spending some time on SO and teh interwebs, I see that what I thought I know as "C++" is actually a mix between C and C++, with large gaps in my knowledge about the more intricate workings of the language. At the same time I also realize that I am intrigued by the language and would like to learn it more.
Googling for "C++ tutorials" reveals a wealth of tutorials, but they are all aimed at complete beginners, spending a lot of time explaining basics that I'm already familiar with. I don't expect that there will be any tutorials made exactly for me, but are there some that have at least been written with an experienced programmer in mind, not spending a lot of time on trivial things, and discussing the finer points of the language and compilers?
| C++ is too complex to be learned through tutorials, you could only scratch the surface that way. Especially the advanced usage of the STL (and templates in general) is usually beyond the scope of online tutorials.
Therefore, I would recommend books: Stroustrup's "The C++ Programming Language", and Scott Meyer's "Effective C++", "More effective C++" and "Effective STL".
You can skip the first few chapters of Stroustrup if you feel confident you know that part already, but it's the best book for going into the details of the language. There should be a law for every aspiring C++ programmer to read at least the first two of Meyer's books I mentioned.
Once you're through with that, check out "Modern C++ Design" by Andrei Alexandrescu for a real eye-opener for what templates can be used for.
Update: In reaction to a downvote eight years later (...), be aware of The Definite C++ Books List. My personal recommendations above hold true, but that list is community-driven.
|
1,770,471 | 1,770,491 | Is it possible to use a RA-iterator out of range? | Consider the following code:
typedef std::vector<int> cont_t; // Any container with RA-iterators
typedef cont_t::const_iterator citer_t; // Random access iterator
cont_t v(100);
const int start = 15; // start > 0.
citer_t it = v.begin() - start; // Do not use *it
int a1 = 20, b1 = 30; // a1, b1 >= start
int a2 = 30, b2 = 40; // a2, b2 >= start
int x = std::min_element(it + a1, it + b1); //
int y = std::min_element(it + a2, it + b2); //
int z = std::min_element(it + 15, it + 25); //
...
Is it possible to use the random access iterator it out of range?
| You'll get assertion condition here according to C++ Standard 24.1.5 Table 76.
|
1,770,636 | 1,770,688 | shared_ptr vs scoped_ptr | scoped_ptr is not copy able and is being deleted out of the scope. So it is kind of restricted shared_ptr. So seems besides the cases when you really need to restrict the copy operation shared_ptr is better to use. Because sometimes you don’t know you need to create a copy of your object or no. So the question is: besides the cases mentioned above, could we consider that shared_ptr is better (or recommended) to use instead of scoped_ptr. Does scoped_ptr work much faster from shared_ptr, or does it have any advantages?
Thanks!
| shared_ptr is more heavyweight than scoped_ptr. It needs to allocate and free a reference count object as well as the managed object, and to handle thread-safe reference counting - on one platform I worked on, this was a significant overhead.
My advice (in general) is to use the simplest object that meets your needs. If you need reference-counted sharing, use shared_ptr; if you just need automatic deletion once you've finished with a single reference, use scoped_ptr.
|
1,770,670 | 1,782,818 | How do I control the text input panel programmatically (TabTip.exe) in Windows Vista/7 | I'm adapting an application for touch screen interface and we want to use the tablet text input panel included in Windows Vista/7, specifically its keyboard. I want to show and hide it as appropriate for my app. Basically I want ShowKeyboard() and HideKeyboard() functions. What's the best way to control this?
I looked at the ITextInputPanel API but I was unable to control the keyboard directly with it (maybe I missed something?). I have also unsuccessfully tried to send window messages to its window.
The application is written in C++/MFC.
Any pointers at all are greatly appreciated.
| I solved the problem. It turns out that Spy++ really is a Windows programmers best friend.
First, the window class of the input panel window turns out to be "IPTip_Main_Window". I use this to get the window handle like so:
HWND wKB = ::FindWindow(_TEXT("IPTip_Main_Window"), NULL);
It turns out that I can just post the same WM_COMMAND messages that its own menu is sending. Most of the operations are available from the menu: dock top, dock bottom and float. The code for sending those messages are:
::PostMessage(wKB, WM_COMMAND, MAKEWPARAM(X,0) , 0);
where X is 10021 for dock bottom, 10023 for dock top and 10020 for floating. The 0 in the high word indicates that the message is sent from a menu.
Finally, I wanted to be able to show and hide the input panel. I noticed that I could turn on a desk band which only includes a single button for toggling the visibility of the input panel. Spy++ing on the messages posted from this button revealed that it sends a global registered window message which is named "TabletInputPanelDeskBandClicked".
Sending this message to the input panel causes it to toggle its visibility.
The HideKeyboard() function now looks like this:
DWORD WM_DESKBAND_CLICKED =
::RegisterWindowMessage(_TEXT("TabletInputPanelDeskBandClicked"));
void HideKeyboard()
{
HWND wKB = ::FindWindow(_TEXT("IPTip_Main_Window"), NULL);
if(wKB != NULL && ::IsWindowVisible(wKB))
{
::PostMessage(wKB, WM_DESKBAND_CLICKED, 0, 0);
}
}
The ShowWindow() function is implemented similarly, but it will also start the keyboard if it is not running.
Update:
It seems that this inter-process messaging is disallowed in Windows Vista/7. When running this command in a non-elevated process it will fail with "access denied". My guess is that this is caused by User Interface Process Isolation (UIPI) protection found in Windows Vista/7. Since the Tablet PC Input Panel is running as a child process of a service it has higher integrity level than user programs, and thus cannot be sent any (or a very limited set of) messages to.
Update:
It turns out that the Tablet PC Input Panel is indeed running in high integrity level, whereas processes started by a limited user account is medium integrity level.
|
1,770,702 | 1,770,735 | Is it difficult to port C++ to C++/CLI? | I suppose you cannot simply compile a C++ application with a C++/CLI compiler. I am wondering if it would be difficult. Has anybody tried this, and if so: were there a lot of modifications needed?
| The situation is a bit like compiling C as C++. Most C will compile as C++, but is a long ways from what you'd think of as exemplary C++, so chances are that you'd want to modify it (often quite a bit) before you used it.
Likewise, most C++ will compile as C++/CLI, but chances are that you'd rather not really use it that way.
|
1,770,707 | 1,771,116 | How do you add a repeated field using Google's Protocol Buffer in C++? | I have the below protocol buffer. Note that StockStatic is a repeated field.
message ServiceResponse
{
enum Type
{
REQUEST_FAILED = 1;
STOCK_STATIC_SNAPSHOT = 2;
}
message StockStaticSnapshot
{
repeated StockStatic stock_static = 1;
}
required Type type = 1;
optional StockStaticSnapshot stock_static_snapshot = 2;
}
message StockStatic
{
optional string sector = 1;
optional string subsector = 2;
}
I am filling out the StockStatic fields while iterating through a vector.
ServiceResponse.set_type(ServiceResponse_Type_STOCK_STATIC_SNAPSHOT);
ServiceResponse_StockStaticSnapshot stockStaticSnapshot;
for (vector<stockStaticInfo>::iterator it = m_staticStocks.begin(); it!= m_staticStocks.end(); ++it)
{
StockStatic* pStockStaticEntity = stockStaticSnapshot.add_stock_static();
SetStockStaticProtoFields(*it, pStockStaticEntity); // sets sector and subsector field to pStockStaticEntity by reading the fields using (*it)
}
But the above code is right only if StockStatic was an optional field and not a repeated field. My questions is what line of code am i missing to make it a repeated field?
| No, you're doing the right thing.
Here's a snippet of my protocol buffer (details omitted for brevity):
message DemandSummary
{
required uint32 solutionIndex = 1;
required uint32 demandID = 2;
}
message ComputeResponse
{
repeated DemandSummary solutionInfo = 3;
}
...and the C++ to fill up ComputeResponse::solutionInfo:
ComputeResponse response;
for ( int i = 0; i < demList.size(); ++i ) {
DemandSummary* summary = response.add_solutioninfo();
summary->set_solutionindex(solutionID);
summary->set_demandid(demList[i].toUInt());
}
response.solutionInfo now contains demList.size() elements.
|
1,770,725 | 2,186,475 | Pointers to members in swig (or Boost::Python) | I made some bindings from my C++ app for python.
The problem is that I use pointers to members (It's for computing shortest path and giving the property to minimize as parameter).
This is the C++ signature:
std::vector<Path> martins(int start, int dest, MultimodalGraph & g, float Edge::*)
This is what I did (from what I understood in the doc):
%constant float Edge::* distance = &Edge::distance;
This is how I call my function from python:
foo.martins(0, 1000, g, foo.distance)
And this is the error I get:
NotImplementedError: Wrong number of arguments for overloaded function 'martins'.
Possible C/C++ prototypes are:
martins(int,int,MultimodalGraph &,float Edge::*)
I have an overloaded method that uses a default 4th paramaters, and it works perfectly.
So is it possible to use pointers to members with swig? If yes, what's the trick? If no, what would be the most elegant way to work arround?
Thank you for your help!
UPDATE: if someone knows if Boost::python does it for sure, I'll switch to it.
| Don't know about SWIG, but in boost::python you can write a wrapper:
bool foo(int x, float* result);
boost::python::tuple foo_wrapper(int x)
{
float v;
bool result = foo(x, &v);
return boost::python::make_tuple(result, v);
}
BOOST_PYTHON_MODULE(foomodule)
{
def("foo", &foo_wrapper);
}
And in python you would:
result, v = foomodule.foo(x)
Since in Python floats are immutable, you can't actually pass one to a method and expect the method to change the float value, so we adapt the code to return a tuple of values instead.
|
1,770,763 | 1,771,043 | boost to_upper function of string_algo doesn't take into account the locale | I have a problem with the functions in the string_algo package.
Consider this piece of code:
#include <boost/algorithm/string.hpp>
int main() {
try{
string s = "meißen";
locale l("de_DE.UTF-8");
to_upper(s, l);
cout << s << endl;
catch(std::runtime_error& e){
cerr << e.what() << endl;
}
try{
string s = "composición";
locale l("es_CO.UTF-8");
to_upper(s, l);
cout << s << endl;
catch(std::runtime_error& e){
cerr << e.what() << endl;
}
}
The expected output for this code would be:
MEISSEN
COMPOSICIÓN
however the only thing I get is
MEIßEN
COMPOSICIóN
so, clearly the locale is not being taken into account. I even try to set the global locale with no success. What can I do?
| std::toupper assumes a 1:1 conversion, so there is no hope for the ß to SS case, Boost.StringAlgo or not.
Looking at StringAlgo's code, we see that it does use the locale (Except on Borland, it seems). So, for the other case, I'm curious: What is the result of toupper('ó', std::locale("es_CO.UTF-8"))on your platform?
Writing the above makes me think about something else: What is the encoding of the strings in your sources? UTF8? In that case, std::toupper will see two code units for 'ó', so there is no hope. Latin1? In that case, using a locale named ".UTF-8" is inconsistent.
|
1,770,780 | 1,770,892 | How to connect to MySQL Database from eMbedded Visual C++ | How can I connect to a remote Mysql database, from Cpp code using Microsoft eMbedded Visual C++ (which is configured for a special board running WindowsCE)? I have downloaded the source files for Mysql C and C++ Connector/APIs but; their 'make' or installation process is pretty complicated and valid only for Visual Studio.
| I have found that, there are no ports of mysql-client to any mobile platform. If anyone has any other information, please feel free to answer this question.
|
1,770,808 | 1,773,410 | Refactoring function pointers to some form of templating | Bear with me as I dump the following simplified code: (I will describe the problem below.)
class CMyClass
{
...
private:
HRESULT ReadAlpha(PROPVARIANT* pPropVariant, SomeLib::Base *b);
HRESULT ReadBeta(PROPVARIANT* pPropVariant, SomeLib::Base *b);
typedef HRESULT (CMyClass::*ReadSignature)(PROPVARIANT* pPropVariant, SomeLib::Base *b);
HRESULT TryFormats(ReadSignature ReadFormat, PROPVARIANT* pPropVariant);
};
inline HRESULT CMyClass::ReadAlpha(PROPVARIANT* pPropVariant, SomeLib::Base *b)
{
if (b)
{
// got a valid Base. Handle generic stuff here.
SetStuff(pPropVariant, b->someInt);
return S_OK;
}
return (b != NULL) ? 0 : -1;
}
inline HRESULT CMyClass::ReadBeta(PROPVARIANT* pPropVariant, SomeLib::Base *b)
{
if (b)
{
SomeLib::FormatA *fa;
SomeLib::FormatB *fb;
if ( fa = dynamic_cast<SomeLib::FormatA*>( b ) )
{
// specific code for FormatA
SetStuff(pPropVariant, fa->getVersion());
return S_OK;
}
else if ( fb = dynamic_cast<SomeLib::FormatB*>( b ) )
{
// specific code for FormatB
SetStuff(pPropVariant, fb->valueForB);
return S_OK;
}
}
return (b != NULL) ? 0 : -1;
}
inline HRESULT CMyClass::TryFormats(ReadSignature ReadFormat, PROPVARIANT* pPropVariant)
{
HRESULT hr;
if (FAILED(hr = (this->*ReadFormat)(pPropVariant, _pFile->formatA())))
if (FAILED(hr = (this->*ReadFormat)(pPropVariant, _pFile->formatC())))
hr = (this->*ReadFormat)(pPropVariant, _pFile->formatD());
return hr;
}
I end up calling this code like:
hr = TryFormats(&CMyClass::ReadAlpha, pPropVar);
Now... the problem is that this is too generic and constrained, especially now that I am trying to refactor this code for use in some other projects. So, this means that I want to place the ReadXxx code in another source file and abuse templating somehow. The TryFormats remains in the class since different classes have different formats they attempt to read.
My current approach is bound to fail due to the dynamic_cast<Derived*> needed for functionality that is not in the Base class, and since I may need to read up to 5 different formats in one class, I really don't want to drag in formats I do not need in the first place. (For example, see above how CMyClass does not support SomeLib::FormatB, yet the ReadBeta() needs to support it and thus forces the compiler to compile all the relevant information in.) In total, I have around 10 different formats I 'support' like this.
How can I properly refactor this code? I don't want to need to rewrite Base functionality for every descendant, nor do I want to put derived specific information into a function that simply takes a Base.
I have tried some things, but all I manage to squeeze out of my compiler are rainbows of errors. Rather than confuse the people here with my attempts, I figured I'd give my (simplified) original working code and allow the experts to draw their own conclusions on how to do this. In reality, there's about 50 of those ReadXxx functions, but they either follow the general structure of the ReadAlpha or ReadBeta functions above. So if someone can show me how to do those, I can without an issue convert my actual code. (I imagine I will need to change TryFormats() definition as well, and that's no problem either - I am just hoping someone can show me how to do get the above example refactored properly.)
Thank you, and my apologies for the long, long question.
| Ok, my previous visitor approach is a history.
I am going to post you entire text of small working program that you can play with.
Assuming that
_pFile->formatA()
_pFile->formatC()
_pFile->formatD()
All declared as
FormatA* formatA()
FormatC* formatC()
FormatD* formatD()
In other words return type is known at compile time, this templatized approach may work for you. And it involves neither function pointers nor dynamic downcasting
//////////////////////////////////////////////////////////////////
// this section is for testing
class Base
{
public:
void ExecuteBase()
{
cout << "Executing Base" << endl;
}
};
class FormatA : public Base
{
public:
void ExecuteAAlpha()
{
cout << "Executing A Alpha" << endl;
}
void ExecuteABeta()
{
cout << "Executing A Beta" << endl;
}
};
class FormatB : public Base
{
public:
void ExecuteBAlpha()
{
cout << "Executing B Alpha" << endl;
}
void ExecuteBBeta()
{
cout << "Executing B Beta" << endl;
}
};
FormatA* GetFormatA()
{
static FormatA cl;
return &cl;
}
FormatB* GetFormatB()
{
static FormatB cl;
return &cl;
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// now begins real code
struct AlphaReader {};
struct BetaReader {};
template <typename READER_TYPE> struct TypeConverter {};
class MyClass
{
public:
template <typename READER_TYPE>
int TryFormats(const READER_TYPE&)
{
TryFormatsImplementation(TypeConverter<READER_TYPE>(), GetFormatA());
TryFormatsImplementation(TypeConverter<READER_TYPE>(), GetFormatB());
return 0;
}
private:
int TryFormatsImplementation(const TypeConverter<AlphaReader>&, Base* pFormat)
{
// here you will call you ReadAlpha which requires Base only
// code below is for testing
cout << "Executing Alpha Reader for Base" <<endl;
pFormat->ExecuteBase();
return 1;
}
int TryFormatsImplementation(const TypeConverter<BetaReader>&, FormatA* pFormat)
{
// here you will call you ReadBeta for FromatA,
// code below is for testing
cout << "Executing Beta Reader for FormatA" <<endl;
pFormat->ExecuteABeta();
return 3;
}
int TryFormatsImplementation(const TypeConverter<BetaReader>&, FormatB* pFormat)
{
// here you will call you ReadBeta for FromatB,
// code below is for testing
cout << "Executing Beta Reader for FormatB" <<endl;
pFormat->ExecuteBBeta();
return 4;
}
};
int main()
{
MyClass cl;
cl.TryFormats(AlphaReader());
cl.TryFormats(BetaReader());
cin.get();
}
After I run this program I get following output which is correct:
Executing Alpha Reader for Base
Executing Base
Executing Alpha Reader for Base
Executing Base
Executing Beta Reader for FormatA
Executing A Beta
Executing Beta Reader for FormatB
Executing B Beta
|
1,771,096 | 1,772,711 | Grabbing memory from another process | in Windows, lets say I have used DLL Injection to get into another process. I have also done some screencaptures of the memory on the process I have injected into and know the location of the data I want to pull out. Lets say there is data in the other process at 0xaaaaaaaa that contains a certain value. How do I grab this value from that process so I can use it in my injecting app? Since I am injected into the process, can I just use something like memcpy?
memcpy(value, 0xaaaaaaaa, 10);
I'm assuming it's probably more involved than this?
EDIT: To the responses below, I don't see how WM_COPYDATA helps me as it is for sending data to another application, not for retrieving data FROM an existing application.
| You should be able to use the ReadProcessMemory function.
See also How to write a Perl, Python, or Ruby program to change the memory of another process on Windows?
|
1,771,117 | 1,771,232 | Why doesn't C++ reimplement C standard functions with C++ elements/style? | For a specific example, consider atoi(const std::string &). This is very frustrating, since we as programmers would need to use it so much.
More general question is why does not C++ standard library reimplement the standard C libraries with C++ string,C++ vector or other C++ standard element rather than to preserve the old C standard libraries and force us use the old char * interface?
Its time consuming and the code to translate data types between these two interfaces is not easy to be elegant.
Is it for compatible reason,considering there was much more legacy C code than these days and preserving these C standard interfaces would make translation from C code to C++ much easier?
In addition,I have heard many other libraries available for C++ make a lot of enhancement and extensions to STL.So does there libraries support these functions?
PS: Considering much more answers to the first specific question, I edit a lot to clarify the question to outline the questions that I am much more curious to ask.
|
Another more general question is why do not STL reimplementate all the standard C libraries
Because the old C libraries do the trick. The C++ standard library only re-implements existing functionality if they can do it significantly better than the old version. And for some parts of the C library, the benefit of writing new C++-implementations just isn't big enough to justify the extra standardization work.
As for atoi and the like, there are new versions of these in the C++ standard library, in the std::stringstream class.
To convert from a type T to a type U:
T in;
U out;
std::stringstream sstr(in);
sstr >> out;
As with the rest of the IOStream library, it's not perfect, it's pretty verbose, it's impressively slow and so on, but it works, and usually it is good enough. It can handle integers of all sizes, floating-point values, C and C++ strings and any other object which defines the operator <<.
EDIT:In addition,I have heard many other libraries avaliable for C++ make a lot of enhancement and extensions to STL.So does there libraries support these functions?
Boost has a boost::lexical_cast which wraps std::stringstream. With that function, you can write the above as:
U out = boost::lexical_cast<U>(in);
|
1,771,156 | 1,771,251 | AVL Tree Code - I don't understand | void insert( const Comparable & x, AvlNode * & t )
{
if( t == NULL )
t = new AvlNode( x, NULL, NULL );
else if( x < t->element )
{
insert( x, t->left );
if( height( t->left ) - height( t->right ) == 2 )
if( x < t->left->element )
rotateWithRightChild( t );
else
doubleWithLeftChild( t );
}
else if( t->element < x )
{
insert( x, t->right );
if( height( t->right ) - height( t->left ) == 2 )
if( x < t->left->element )
rotateWithRightChild( t );
else
doubleWithLeftChild( t );
}
else
; // Duplicate; do nothing
t->height = max( height( t->left ), height( t->right ) ) + 1;
}
int height( AvlNode *t ) const { return t == NULL ? -1 : t->height; }
How can they cal the height of tree ?
1
0
-1
height(-1) - height(null) = 1 ?? Not balance ?
| It's not 100% clear what you're asking. The code
AvlNode * & t
declares t to be a reference to a non-const pointer. So, the function insert may change the pointer object of the caller. Since pointers may be null the code probably uses a function called height as a shortcut to handle the special case of null pointers:
inline int height(AvlNode * tree) {
return tree ? tree->height : 0;
}
(just my guess of what height could look like)
Added after you editited your question:
It seems each node posesses a member called height which is kept in sync and reflects the maximum length of the path from the current node to a leaf. Since a null pointer doesn't point to a node, the subtree would be empty which explains the special case in height() that returns -1.
|
1,771,222 | 1,771,402 | Effect of exit function in Windows Service Programs | I have a program that is a windows service. It is started by StartServiceCtrlDispatcher function. It's network server that accepts user's inputs as command for controlling purposes. Now, I want it to have the ability to be shutdown by users, i.e. when user type a "quit" command, the service will stop. (Don't worry about how the service can be started again.) Can I just use "exit" function in standard library or do I need to use "ControlService" function?
| You should use the ControlService() function to stop the service, and then return from program flow normally if this should also cause the process to exit.
ControlService Function @ MSDN
exit() will cause process termination, which will definitely kill a process that hosts 1 service. However, this is undesirable for stopping a service in a process that hosts more than 1 service. Also, it is undefined whether other observers monitoring your service will receive graceful notification of the service stop if you use exit(). Other operating libraries in your process that you may have loaded, may also fail to stop correctly if you use exit().
exit, _exit @ MSDN
|
1,771,302 | 1,771,347 | Efficient passing of std::vector | When a C++ function accepts an std::vector argument, the usual pattern is to pass it by const reference, such as:
int sum2(const std::vector<int> &v)
{
int s = 0;
for(size_t i = 0; i < v.size(); i++) s += fn(v[i]);
return s;
}
I believe that this code results in double dereferencing when the vector elements are accessed, because the CPU should first dereference v to read the pointer to the first element, which pointer needs to be dereferenced again to read the first element. I would expect that it would be more efficient to pass a shallow copy of the vector object on the stack. Such shallow copy would encapsulate a pointer to the first element, and the size, with the pointer referencing the same memory area as the original vector does.
int sum2(vector_ref<int> v)
{
int s = 0;
for(size_t i = 0; i < v.size(); i++) s += fn(v[i]);
return s;
}
Similar performance, but much less convenience could be achieved by passing a random access iterator pair. My question is: what is flawed with this idea? I expect that there should be some good reason that smart people accept to pay the performace cost of vector reference, or deal with the inconvenience of iterators.
Edit: Based on the coments below, please consider the situation if I simply rename the suggested vector_ref class to slice or range. The intention is to use random-access iterator pairs with more natural syntax.
|
I believe that this code results in double dereferencing when the vector elements are accessed
Not necessarily. Compilers are pretty smart and should be able to eliminate common subexpressions. They can see that the operator [] doesn't change the 'pointer to the first element', so they have no need make the CPU reload it from memory for every loop iteration.
|
1,771,386 | 1,771,453 | Explain the Need for Mutexes in Locales, Please | Reading the question Why doesn’t C++ STL support atoi(const string& ) like functions?, I encountered a comment which warned that GCC (at least) has a bug that can slow down multi-threaded applications which use ostringstream frequently. This is apparently due to a mutex 'needed' by the C++ locale machinery.
Given my recent interest in globalization practices, I wonder if anyone can explain to me why a locale object would need a mutex? What is it that can be changed in a locale that needs a mutex? Shouldn't it be a read-only facility?
| It's really an implementation issue, but std::locale has a static function that retrieves and set the 'global' locale. The global locale is defined to be used in several areas of the standard library which implies that there must be a global locale somewhere.
In implementations that support threads it is very likely that this global locale needs to be protected via some sort of locking mechanism to prevent simultaneous access between threads from causing undesired behaviour.
As the current standard does not explicitly deal with threading at all, it's a set implementation choices as to how (or if) this locking mechanism is implemented and whether other shared data and locks are required.
|
1,771,518 | 1,771,593 | Ensuring certain private functions can only be called from a locked state | Say I have a class A:
class A {
public:
A();
void fetch_data() { return 1; }
void write_x_data() {
// lock this instance of A
private_function1_which_assumes_locked();
private_function2_which_assumes_locked();
// unlock this instance of A
}
void write_y_data() {
// lock this instance of A
private_function1_which_assumes_locked();
// unlock this instance of A
}
private:
void private_function1_which_assumes_locked();
void private_function2_which_assumes_locked();
};
I want to guarantee that private_function*_which_assumed_locked() can never be called unless A is locked.
What's the best way to accomplish this? I've got 5 or so public functions which need locking. These functions never call into each other, so I'm not worried about deadlocking with these. Combined, these 5 public functions call into around 15 different private functions which need to assume the object is in a locked state. Obviously, I can't lock the private functions, since I'd get deadlocks.
Feel free to provide answers in reasonably high-level abstractions, assuming the existences of Mutexes and Scopeguards.
In Python I might do something like this with decorators:
class locked_method(object):
def __init__(self, f):
self.f = f
def __call__(self):
# Do whatever is needed to lock
self.f()
# Do whatever is needed to unlock
class checklocked(object):
def __init__(self, f):
self.f = f
def __call__(self):
# check locked, if not, don't call self.f(),
# and yell at me loudly for screwing up.
self.f()
@locked_method
def func1():
__function_which_assumes_locked()
@checklocked
def __function_which_assumes_locked():
pass
NB: I've not done much in the way of Python, so feel free to comment if my Python is wrong/stupid, but the point of this question is more the best way to accomplish this sort of thing in C++, so hopefully the Python provided is enough to give you an idea of what I want to do.
| You could use a locker class, and require one to exist in order to call the private functions:
class A
{
public:
void write()
{
Lock l(this);
write(l);
}
private:
void lock();
void unlock();
void write(const Lock &);
class Lock
{
public:
explicit Lock(A *a) : parent(a) {parent->lock();}
~Lock() {parent->unlock();}
private:
A *parent;
};
};
|
1,771,692 | 1,772,605 | When does template instantiation bloat matter in practice? | It seems that in C++ and D, languages which are statically compiled and in which template metaprogramming is a popular technique, there is a decent amount of concern about template instantiation bloat. It seems to me like mostly a theoretical concern, except on very resource-constrained embedded systems. Outside of the embedded space, I have yet to hear of an example of someone being able to demonstrate that it was a problem in practice.
Can anyone provide an example outside of severely resource-limited embedded systems of where template instantiation bloat mattered in practice and had measurable, practically significant negative effects?
| There's little problem in C++, because the amount of template stuff you can do in C++ is limited by their complexity.
In D however ... before CTFE (compile-time function evaluation) existed, we had to use templates for string processing. This is also the reason big mangled symbols are compressed in DMD - the strings used as template arguments become part of the mangled symbol names, and when instantiating templates with longer segments of code (for instance) the resulting symbol sizes would spectacularly explode the object format.
It's better nowadays. But on the whole, templates still cause a lot of bloat for a simple reason - they parse faster and are more powerful than in C++, so people naturally use them a lot more (even in cases that technically wouldn't need templates). I must admit I'm one of the prime offenders here (take a look at tools.base if you like, but be sure to keep a barf bag handy - the file is effectively 90% template code).
|
1,771,980 | 1,772,915 | Porting linux socket application to windows usins MsDev | Is there openly available headers which can be used to compile linux socket application (using socket/udp/ip headers). they should define structures like sa_family_t,in_port_t
Mandatory is to use Msdev and not cygwin/gcc or mingw compiler.
| As far as I know, there is no easy way to do this. Windows provides an entirely different set of system calls than linux, as well as a different method for handling sockets.
|
1,772,395 | 1,772,474 | C++ bool array as bitfield? | let's say i need to store 8 bools in a struct, but i want to use for them only 1 byte together, then i could do something like this:
struct myStruct {
bool b1:1;
bool b2:1;
bool b3:1;
bool b4:1;
bool b5:1;
bool b6:1;
bool b7:1;
bool b8:1;
};
and with this i could do things like
myStruct asdf;
asdf.b3=true;
asdf.b4=false;
if(asdf.b1)
...
is this correct so far? (i don't know it actually, i never used bitfields before)
ok - but is it also possible to create a static array of 8 bools such that they will use only 8 bits but i will still be able to adress them by index?
something like
struct myStruct {
public:
bool b[8]:8;
};
maybe? (with this, i get a error C2033)
thanks for the help!
| I would recommend using a std::bitset That way you could simply declare:
std::bitset<8> asdf;
and use it with [].
asdf[0] = true;
asdf[3] = false;
|
1,772,400 | 1,772,492 | boost split compile issue | I have the following code snippet. I am compiling using the sun studio 12 compiler and have tried boost 1.33 and 1.39
#include <boost/algorithm/string.hpp>
#include <string>
#include <vector>
using namespace boost;
using namespace std;
int main(int argc, char* argv[])
{
string exbyte = "0x2430";
string exbytes = "0x2430,2430";
typedef vector< string > SplitVec;
SplitVec res1 ;
split(res1 , exbyte, is_any_of(",") );
return 0
}
I get the following compile error:
"/bb/source/boost/boost_1_39_0/boost/algorithm/string/iter_find.hpp", line 175: Error, nomatchoverin: Could not find a match for std::vector::vector(boost::transform_iterator, boost::algorithm::split_iterator, boost::use_default, boost::use_default>, boost::transform_iterator, boost::algorithm::split_iterator, boost::use_default, boost::use_default>) needed in boost::algorithm::iter_split, std::string, boost::algorithm::detail::token_finderF>>(std::vector&, std::string &, boost::algorithm::detail::token_finderF>)
If anybody has thoughts on this that would be awesome. Since I am cotemplateing strtok(only kidding)
| Other than the missing semi-colon after return 0, which I assume is an unrelated typo, your code compiles fine for me, using gcc 4.3.2.
According to the documentation for boost::split, you're using the function correctly, so I don't think this is a coding error. Are you sure you have boost installed correctly?
Edit: It may be that Boost doesn't support your particular compiler, so parts of boost may not work for you. See here for a list of supported compilers, along with various issues which affect each compiler.
|
1,772,485 | 1,772,504 | Printf and hex values | So, I have a value of type __be16 (2 bytes). In hex, the value is represented as 0x0800 or 2048 in decimal. (16^2 * 8)
So, when I printf this; I do this:
printf("%04X", value); //__be16 value;
//Print a hex value of at least 4 characters, no padding.
output:
0008
printf("%i", value); //Print an integer.
output:
8
I should be getting
0800 and 2048 respectively, what am I doing wrong?
| My guess is that value is 8. :-)
Are you on a little endian machine, such as x86? I'm going to guess that by be16 you mean that the value is big endian and you need to swap the bytes.
|
1,772,672 | 1,772,724 | Are there compiler flags to get malloc to return pointers above the 4G limit for 64bit testing (various platforms)? | I need to test code ported from 32bit to 64bit where pointers are cast around as integer handles, and I have to make sure that the correct sized types are used on 64 bit platforms.
Are there any flags for various compilers, or even flags at runtime which will ensure that malloc returns pointer values greater than the 32bit limit?
Platforms I'm interested in:
Visual Studio 2008 on Windows XP 64, and other 64 bit windows
AIX using xLC
64bit gcc
64bit HP/UX using aCC
Sample Application that allocates 4GB
So thanks to R Samuel Klatchko's answer, I was able to implement a simple test app that will attempt to allocate pages in the first 4GB of address space. Hopefully this is useful to others, and other SO users can give me an idea how portable/effective it is.
#include <stdlib.h>
#include <stdio.h>
#define UINT_32_MAX 0xFFFFFFFF
#ifdef WIN32
typedef unsigned __int64 Tuint64;
#include <windows.h>
#else
typedef unsigned long long Tuint64;
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#endif
static void* Allocate(void* pSuggested, unsigned int PageSize)
{
#ifdef WIN32
void* pAllocated = ::VirtualAlloc(pSuggested, PageSize, MEM_RESERVE ,PAGE_NOACCESS);
if (pAllocated)
{
return pAllocated;
}
return (void*)-1;
#else
void* pAllocated = ::mmap(pSuggested,
PageSize,
PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
-1,
0);
if (pAllocated == MAP_FAILED)
{
pAllocated = (void*)-1;
}
return pAllocated;
#endif
}
static void Deallocate(void* pRegion, unsigned int PageSize)
{
#ifdef WIN32
::VirtualFree(pRegion,0,MEM_RELEASE);
#else
::munmap(pRegion,PageSize);
#endif
}
static void Gobble32bitAddressSpace()
{
#ifdef WIN32
SYSTEM_INFO SysInfo;
::GetSystemInfo(&SysInfo);
unsigned int PageSize = SysInfo.dwAllocationGranularity;
#else
unsigned int PageSize = ::sysconf(_SC_PAGE_SIZE);
#endif
unsigned int AllocatedPages = 0;
unsigned int SkippedPages = 0;
void *pStart = 0;
while( ((Tuint64)pStart) < UINT_32_MAX)
{
void* pAllocated = Allocate(pStart, PageSize);
if (pAllocated != (void*)-1)
{
if (pAllocated == pStart)
{
//Allocated at expected location
AllocatedPages++;
}
else
{
//Allocated at a different location
//unallocate and consider this page unreserved
SkippedPages++;
Deallocate(pAllocated,PageSize);
}
}
else
{
//could not allocate at all
SkippedPages++;
}
pStart = (char*)pStart + PageSize;
}
printf("PageSize : %u\n",PageSize);
printf("Allocated Pages : %u (%u bytes)\n",AllocatedPages,PageSize*AllocatedPages);
printf("Skipped Pages : %u (%u bytes)\n",SkippedPages,SkippedPages*PageSize);
}
int main()
{
Gobble32bitAddressSpace();
//Try to call malloc now and see if we get an
//address above 4GB
void* pFirstMalloc = ::malloc(1024);
if (((Tuint64)pFirstMalloc) >= UINT_32_MAX)
{
printf("OK\n");
}
else
{
printf("FAIL\n");
}
return 0;
}
| One technique I have used in the past is to allocate enough memory at startup that all the address space below the 4GB limit is used up. While this technique does rely on malloc first using the lower parts of the address space, this was true on all the platforms I work on (Linux, Solaris and Windows).
Because of how Linux uses overcommit, if you don't touch the allocated space below the 4GB limit, you won't use up any virtual memory.
On Windows, you can use VirtualAlloc() with the MEM_RESERVE flag to use up address space without allocating any actual storage.
|
1,772,679 | 1,773,163 | Anybody tried to compile Go on Windows?, It appears to now support generating PE Format binaries | http://code.google.com/r/hectorchu-go-windows/source/list
If you could compile it successfully, I like to know the procedures of how to.
| Assuming you are using Hector's source tree:
Install MinGW and MSYS, along with MSYS Bison and any other tools you think you'll find useful (vim, etc).
Install ed from the GNUWin32 project.
Install Python and Mercurial.
Clone the [hectorchu-go-windows mercurial repository](https://hectorchu-go-windows.googlecode.com/hg/ hectorchu-go-windows) to C:\Go.
Run an MSYS shell (or rxvt). The rest of these are bash commands...
mkdir $HOME/bin
export PATH=$HOME/bin:$PATH
export GOROOT=C:\\Go
export GOARCH=386
export GOOS=mingw
cd /c/Go/src
./all.bash
Correct errors as it spits them out at you, repeat step 10 until it starts building.
It's the same idea as on Linux or MacOS, basically.
However, I still stand by what I said in my comment above: this isn't necessarily going to generate anything that actually works yet. You'd be better served by waiting until this effort has merged into the main Go tree before tackling it, unless your interest is in assisting with the porting effort.
Update: there is now a mostly-functional pre-built windows port available, for those not interested in building the compiler themselves. However, given the rate of change of the project, the lack of formal releases (other than the hg "release" tag), and the possibility of Hector's changes being merged into the main branch soon, keeping up with development via source builds is likely to produce better results over time.
|
1,772,838 | 1,772,891 | invalid initialization of non-const reference of type ‘int&' from a temporary of type 'MyClass<int>::iterator*' | I'm getting the following error from g++ while trying to add iterator support for my linked list class.
LinkedList.hpp: In member function ‘Type& exscape::LinkedList<Type>::iterator::operator*() [with Type = int]’:
tests.cpp:51: instantiated from here
LinkedList.hpp:412: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘exscape::LinkedList<int>::iterator*’
Likely relevant code snippets:
LinkedList.hpp:
template <typename Type>
class LinkedList {
private:
struct node {
struct node *prev;
struct node *next;
Type data;
};
public:
class iterator : public std::iterator<...> {
node *p;
public:
Type &operator*();
};
...
};
template <typename Type>
LinkedList<Type>::iterator::iterator(struct node *in_node) : p(in_node) {}
template <typename Type>
inline Type &LinkedList<Type>::iterator::operator*() {
return this-p->data; ///// Line 412
}
tests.cpp:
...
LinkedList<int> l1;
...
LinkedList<int>::iterator it;
for (it = l1.begin(); it != l1.end(); ++it) {
std::cout << "Element: " << *it << std::endl; ///// Line 51
}
I've googled (and searched SO, of course), and checked my code to no avail - either I'm missing something basic (aka. doing something stupid), or I'm missing the knowledge required. Any advice?
| you're returning a reference on a temporary object : this - p->data (I emphasized the typo) computes a pointer interval, and the result of the operation is a temporary rvalue: you can't take a reference from it.
Just remove the typo:
this->p->data;
|
1,773,079 | 1,773,097 | Segmentation Fault With Char Array and Pointer in C on Linux | So I have the following program:
int main(){
char* one = "computer";
char two[] = "another";
two[1]='b';
one[1]='b';
return 0;
}
It segfaults on the line "one[1]='b'" which makes sense because the memory that the pointer "one" points to must be in read only memory. However, the question is why doesn't the line "two[1]='b'" segfault? Looking at the assembly output from gcc:
.file "one.c"
.section .rodata
.LC0:
.string "computer"
.LC1:
.string "another"
.text
.globl main
.type main, @function
main:
We see that both strings are in the rodata section so they are readonly. So then how come the line "two[1]='b' does not segfault?
| one points directly to the string located in a read-only page. On the other hand, two is an array allocated on the stack and is initialized with some constant data. At run time, the string in the read only section of the executable will be copied to the stack. What you are modifying is the copy of that string on the stack, not the read-only memory page.
At a higher level perspective, from the language point of view, "abcd" is an expression of type const char* and not char*. Thus, modifying the value pointed by such an expression results in undefined behavior. The statement char* one = "something"; merely stores the pointer to the string in a variable (unsafely, since it's casting away const modifier). The char two[] = "something"; is totally different. It's actually declaring an array and initializing it, much like int a[] = {1,2,3};. The string in quotes here is the initialization expression.
|
1,773,381 | 1,961,610 | What is the "Shell Namespace" way to create a new folder? | Obviously this is trivial to do with win32 api - CreateDirectory(). But I'm trying to host an IShellView, and would like to do this the most shell-oriented way. I would have thought that there would be a createobject or createfolder or some such from an IShellFolder. But neither IShellView nor IShellFolder nor even IFolderView seem to have anything quite like this.
Is there a Shell-programming way to create a new folder? Or do I need to create a folder using a pathname, the old-fashioned way?
If I have to do it via CreateDirectory(), then my next question might be: any ideas as to how to get the IShellView / IFolderView to actually see this new object and display it to the user?
Motivation: Creating my own File Dialog replacement and I want to provide the "new folder" toolbar icon functionality of the standard XP-style file dialog.
EDIT: I went ahead and created something that basically works, using CreateDirectory. However, I'm still hoping that there's a better way to do this, but so that you can see how that works, and to offer better ideas as to solve this issue better:
PidlUtils::Pidl pidl(m_folder);
CFilename folderName(GetDisplayNameOf(pidl), "New Folder");
for (int i = 2; folderName.Exists(); ++i)
folderName.SetFullName(FString("New Folder (%d)", i));
if (!CPathname::Create(folderName, false))
throw CContextException("Unable to create a new folder here: ");
// get the PIDL for the newly created folder
PidlUtils::Pidl pidlNew;
#ifdef UNICODE
const wchar_t * wszName = folderName.c_str();
#else
wchar_t wszName[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, folderName.GetFullName(), -1, wszName, MAX_PATH);
#endif
m_hresult = m_folder->ParseDisplayName(NULL, NULL, wszName, NULL, pidlNew, NULL);
if (FAILED(m_hresult))
throw CLabeledException(FString("Unable to get the PIDL for the new folder: 0x%X", m_hresult));
// upgrade our interface so we can select & rename it
CComQIPtr<IShellView2> sv2(m_shell_view);
if (!sv2)
throw CLabeledException("Unable to obtain the IShellView2 we need to rename the newly created folder.");
// force it to see thew new folder
sv2->Refresh();
// select the new folder, and begin the rename process
m_hresult = sv2->SelectAndPositionItem(pidlNew, SVSI_EDIT|SVSI_DESELECTOTHERS|SVSI_ENSUREVISIBLE|SVSI_POSITIONITEM, NULL);
if (FAILED(m_hresult))
throw CLabeledException(FString("Unable to select and position the new folder item: 0x%X", m_hresult));
| Shell folders usually implement the IStorage interface, so this is pretty simple. For example, the following creates a folder named "abcd" on the desktop:
CComPtr<IShellFolder> pDesktop;
HRESULT hr = SHGetDesktopFolder(&pDesktop);
if (FAILED(hr)) return;
CComQIPtr<IStorage> pStorage(pDesktop);
if (!pStorage) return;
CComPtr<IStorage> dummy;
hr = pStorage->CreateStorage(L"abcd", STGM_FAILIFTHERE, 0, 0, &dummy);
|
1,773,426 | 1,774,512 | convert a list of structs from c# to c++ | I have the following c# code
static void Main(string[] args)
{
List<Results> votes = new List<Results>();
}
public struct Results
{
public int Vote1;
public int Vote2;
public int Vote3;
public Candidate precinctCandidate;
};
public class Candidate
{
public Candidate()
{
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string lastName;
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
I want to convert that code into Visual c++ CLR, Thanks
| Here is a direct translation of your code to C++/CLI:
using namespace System;
using namespace System::Collections::Generic;
public ref class Candidate
{
public:
Candidate()
{
}
property String^ Name
{
String^ get() { return this->name; }
void set(String^ value) { this->name = value; }
}
property String^ LastName
{
String^ get() { return this->lastName; }
void set(String^ value) { this->lastName = value; }
}
private:
String^ name;
String^ lastName;
};
public value class Results
{
public:
Int32 Vote1;
Int32 Vote2;
Int32 Vote3;
Candidate^ precinctCandidate;
};
int main(array<String^>^ args)
{
List<Results> votes = gcnew List<Results>();
return 0;
}
|
1,773,470 | 1,773,488 | What is the Code Definition Window in Visual C++ 2008 Express? | I am working on the Sphere Online Judge problems (OK I am only on my 2nd lol) and using VC++ 2008 express and have just noticed the "code definition window". What exactly does this thing do? Is it any use to a beginner like me?
| The code definition window gives you additional context for the code you have the cursor over.
For example if you have the cursor over Cat in the following code:
Cat c;
Then it will display the definition of the Cat class in the code definition window.
If you have the following code:
c.meow();
And you have the cursor over c, it will show you where c was defined. (i.e. the line of code: Cat c;)
Instead of using this window, you can simply right click on any part of code and select go to definition.
|
1,773,526 | 1,773,620 | In-place C++ set intersection | The standard way of intersecting two sets in C++ is to do the following:
std::set<int> set_1; // With some elements
std::set<int> set_2; // With some other elements
std::set<int> the_intersection; // Destination of intersect
std::set_intersection(set_1.begin(), set_1.end(), set_2.begin(), set_2.end(), std::inserter(the_intersection, the_intersection.end()));
How would I go about doing an in-place set intersection? That is, I want set_1 to have the results of the call to set_intersection. Obviously, I can just do a set_1.swap(the_intersection), but this is a lot less efficient than intersecting in-place.
| I think I've got it:
std::set<int>::iterator it1 = set_1.begin();
std::set<int>::iterator it2 = set_2.begin();
while ( (it1 != set_1.end()) && (it2 != set_2.end()) ) {
if (*it1 < *it2) {
set_1.erase(it1++);
} else if (*it2 < *it1) {
++it2;
} else { // *it1 == *it2
++it1;
++it2;
}
}
// Anything left in set_1 from here on did not appear in set_2,
// so we remove it.
set_1.erase(it1, set_1.end());
Anyone see any problems? Seems to be O(n) on the size of the two sets. According to cplusplus.com, std::set erase(position) is amortized constant while erase(first,last) is O(log n).
|
1,773,757 | 1,773,966 | Checking for list membership using the STL and a unary function adapted functor | I've attempted to write a brief utility functor that takes two std::pair items and tests for their equality, but disregarding the ordering of the elements. Additionally (and this is where I run into trouble) I've written a function to take a container of those std::pair items and test for membership of a given pair argument in a the container.
/* A quick functor way to check the identity of the two items of a pair to see if each pair contains the same items regardless of order */
template <class T>
class EqualPairs : public std::binary_function<T,T,bool> {
T arg2;
public:
explicit EqualPairs (const T& x) : arg2(x) { }
bool operator() (const T& arg1) {
bool same = false;
if (arg1 == arg2 || (arg1.first == arg2.second && arg1.second == arg2.first))
same = true;
return same;
}
};
/* checks to see if the give pair p is a member of the list of pairs l. The pairs are compared disregarding the order of the pair elements (i.e. (4,2) == (2,4)) */
template <class P>
bool PairListMember (const P& p, const std::vector<P>& l)
{
std::vector<P>::iterator it;
it = find_if (l.begin(), l.end(), EqualPairs<P>(p));
bool member_of_list = (it != l.end()) ? true : false;
return member_of_list;
}
I couldn't think of a clean way to allow for generic container selection, so I hard-coded a std::vector as the container type, for now. Help on making the container type generic would also be appreciated, but for now I'd just like to get the above to compile and work. The error I get is:
In function ‘bool PairListMember(const P&, const std::vector<P, std::allocator<_CharT> >&)’:
error: expected `;' before ‘it’
error: ‘it’ was not declared in this scope
In function ‘bool PairListMember(const P&, const std::vector<P, std::allocator<_CharT> >&) [with P = std::pair<int, int>]’:
error: dependent-name ‘std::vector<P,std::allocator<_CharT> >::iterator’ is parsed as a non-type, but instantiation yields a type
note: say ‘typename std::vector<P,std::allocator<_CharT> >::iterator’ if a type is meant
changing the code by adding a 'typename' as suggested only results in the following errors:
error: no match for ‘operator=’ in ‘it = std::find_if [with _InputIterator = __gnu_cxx::__normal_iterator<const std::pair<int, int>*, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >, _Predicate = EqualPairs<std::pair<int, int> >](((const std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >*)l)->std::vector<_Tp, _Alloc>::begin [with _Tp = std::pair<int, int>, _Alloc = std::allocator<std::pair<int, int> >](), ((const std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >*)l)->std::vector<_Tp, _Alloc>::end [with _Tp = std::pair<int, int>, _Alloc = std::allocator<std::pair<int, int> >](), EqualPairs<std::pair<int, int> >(((const std::pair<int, int>&)((const std::pair<int, int>*)p))))’
/usr/include/c++/4.2/bits/stl_iterator.h:637: note: candidates are: __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >& __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >::operator=(const __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >&)
| There are a couple of issues with your EqualPairs template. It derives from binary_function but isn't actually a binary_function because operator() only takes one argument. You can (and should) make operator() const as it doesn't modify the EqualPairs object.
I think that you can simplify it somewhat.
template<class T>
struct EqualPairs : public std::binary_function<T, T, bool>
{
bool operator()(const T& lhs, const T& rhs) const
{
return lhs == rhs || lhs.first == rhs.second && lhs.second == rhs.first;
}
};
Then you can use std::bind1st (or std::bind2nd) to make a predicate out of your binary function and the input parameter. Also, by making the function a 'one liner' you don't actually need to declare a temporary variable for the iterator, so getting const and typename correct isn't an issue.
template <class P>
bool PairListMember (const P& p, const std::vector<P>& l)
{
return l.end() != std::find_if(l.begin(), l.end(), std::bind1st(EqualPairs<P>(), p));
}
You can make this template more generic by taking an iterator type as a template parameter. This removes your dependency on std::vector.
template <class Iter>
bool PairListMember(const typename std::iterator_traits<Iter>::value_type& p, Iter first, Iter last)
{
return last != std::find_if(first, last, std::bind1st(EqualPairs<typename std::iterator_traits<Iter>::value_type>(), p));
}
|
1,773,897 | 1,773,918 | Why is argc an 'int' (rather than an 'unsigned int')? | Why is the command line arguments count variable (traditionally argc) an int instead of an unsigned int? Is there a technical reason for this?
I've always just ignored it when trying rid of all my signed unsigned comparison warnings, but never understood why it is the way that it is.
| The fact that the original C language was such that by default any variable or argument was defined as type int, is probably another factor. In other words you could have:
main(argc, char* argv[]); /* see remark below... */
rather than
int main(int argc, char *argv[]);
Edit: effectively, as Aaron reminded us, the very original syntax would have been something like
main(argc, argv) char **argv {... }
Since the "prototypes" were only introduced later. That came roughly after everyone had logged a minimum of at least 10 hours chasing subtle (and not so subtle) type-related bugs
|
1,774,129 | 1,774,140 | How can we find the process ID of a running Windows Service? | I'm looking for a good way to find the process ID of a particular Windows Service.
In particular, I need to find the pid of the default "WebClient" service that ships with Windows. It's hosted as a "local service" within a svchost.exe process. I see that when I use netstat to see what processes are using what ports it lists [WebClient] under the process name, so I'm hoping that there is some (relatively) simple mechanism to find this information.
| QueryServiceStatusEx returns a SERVICE_STATUS_PROCESS, which contains the process identifier for the process under which the service is running.
You can use OpenService to obtain a handle to a service from its name.
|
1,774,187 | 1,774,195 | Is the order of initialization guaranteed by the standard? | In the following code snippet d1's initializer is passed d2 which has not been constructed yet (correct?), so is the d.j in D's copy constructor an uninitialized memory access?
struct D
{
int j;
D(const D& d) { j = d.j; }
D(int i) { j = i; }
};
struct A
{
D d1, d2;
A() : d2(2), d1(d2) {}
};
Which section of C++ standard discusses order of initialization of data members?
| I don't have the standard handy right now so I can't quote the section, but structure or class member initialisation always happens in declared order. The order in which members are mentioned in the constructor initialiser list is not relevant.
Gcc has a warning -Wreorder that warns when the order is different:
-Wreorder (C++ only)
Warn when the order of member initializers given in the code does
not match the order in which they must be executed. For instance:
struct A {
int i;
int j;
A(): j (0), i (1) { }
};
The compiler will rearrange the member initializers for i and j to
match the declaration order of the members, emitting a warning to
that effect. This warning is enabled by -Wall.
|
1,774,222 | 1,774,228 | Taking screenshot of a specific window - C++ / Qt | In Qt, how do I take a screenshot of a specific window (i.e. suppose I had Notepad up and I wanted to take a screenshot of the window titled "Untitled - Notepad")?
In their screenshot example code, they show how to take a screenshot of the entire desktop:
originalPixmap = QPixmap::grabWindow(QApplication::desktop()->winId());
How would I get the winId() for a specific window (assuming I knew the window's title) in Qt?
Thanks
| I'm pretty sure that's platform-specific. winIds are HWNDs on Windows, so you could call FindWindow(NULL, "Untitled - Notepad") in the example you gave.
|
1,774,661 | 1,774,672 | create singleton class that has constructor which accepts arguments that are evaluated runtime | I want to have singleton class that its object is not statically created. having the following code, when I call ChromosomePool::createPool() I get the following error message :
--> ChromosomePool.h:50: undefined reference to `myga::ChromosomePool::pool' <--
Can anyone please tell me how can I solve the problem ?
class ChromosomePool {
private:
double * array;
const int len;
const int poolSize;
const int chromosomeLength;
static ChromosomePool* pool;
ChromosomePool(int size_of_pool, int length_of_chromosom):
poolSize(size_of_pool) , chromosomeLength(length_of_chromosom),
len(size_of_pool*length_of_chromosom){
array = new double[len];
}
public:
static void createPool(int size_of_pool, int length_of_chromosom) {
if(pool) {
DUMP("pool has already been initialized.");
exit(5);
}
pool = new ChromosomePool(size_of_pool,length_of_chromosom);
}
static void disposePool() {
if( !pool ) {
DUMP("Nothing to dispose");
exit(5);
}
pool ->~ChromosomePool();
pool = NULL;
}
static ChromosomePool* instace() {
if( !pool ) {
DUMP("Using pool before it is initialized");
exit(5);
}
return pool;
}
~ChromosomePool() {
delete[] array;
}
};
| Static members have to be defined, you are only declaring pool as existing somewhere.
Put this in the corresponding source file:
ChromosomePool* ChromosomePool::pool = 0;
Here is the entry in C++ FAQ lite for the subject.
|
1,774,685 | 1,774,695 | boost linker errors -regular expressions - c++ | hi am trying to compile a simple program in boost library but i keep getting linker errors
#include <iostream>
#include <string>
#include <boost\regex.hpp> // Boost.Regex lib
using namespace std;
int main( ) {
std::string s, sre;
boost::regex re;
while(true)
{
cout << "Expression: ";
cin >> sre;
if (sre == "quit")
{
break;
}
cout << "String: ";
cin >> s;
try
{
// Set up the regular expression for case-insensitivity
re.assign(sre, boost::regex_constants::icase);
}
catch (boost::regex_error& e)
{
cout << sre << " is not a valid regular expression: \""
<< e.what() << "\"" << endl;
continue;
}
if (boost::regex_match(s, re))
{
cout << re << " matches " << s << endl;
}
}
}
but i keep getting linker errors
[Linker error] undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned int)'
How can i solve this?
Ps: am using devcpp ide and i installed boost from www.devpaks.org
| If you get the Boost libraries from the official source distribution, make sure you build the binaries using bjam (a lot of the boost libraries are header-only and don't require you to do this; the regex library needs to be built). It looks like the libraries are distributed with the devpack release, so this shouldn't be a problem for you.
Make sure that you have the boost lib directory in your linker path. With gcc, you can use the -L compiler flag:
gcc [whatever you normally put here] -L/path/to/boost/lib/directory
or for Visual C++, you can just add the lib directory to the "Additional Library Directories" on the "Linker > General" property page for your project.
With the Visual C++ linker, you don't need to explicitly tell the linker which particular Boost libraries to pull in; the Boost headers contain directives to have the correct ones pulled in automatically. For g++, you need to specify the libraries, so you'll need to go look up the name of the regex library and add the appropriate compiler directive to link against it (-llibname (that's a lowercase L)).
|
1,774,882 | 1,775,109 | C++ instantiate templates in loop | I have have a factory class, which needs to instantiate several templates with consecutive template parameters which are simple integers. How can I instantiate such template functions without unrolling the entire loop?
The only thing that can think of is using boost pre-processor. Can you recommend something else, which does not depend on the preprocessor?
thanks
| Template parameters have to be compile-time constant. Currently no compiler considers a loop counter variable to be a constant, even after it is unrolled. This is probably because the constness has to be known during template instantation, which happens far before loop unrolling.
But it is possible to construct a "recursive" template and with a specialization as end condition. But even then the loop boundary needs to be compile time constant.
template<int i>
class loop {
loop<i-1> x;
}
template<>
class loop<1> {
}
loop<10> l;
will create ten template classes from loop<10> to loop<1>.
|
1,774,911 | 1,775,092 | How to design a C++ API for binary compatible extensibility | I am designing an API for a C++ library which will be distributed in a dll / shared object. The library contains polymorhic classes with virtual functions. I am concerned that if I expose these virtual functions on the DLL API, I cut myself from the possibility of extending the same classes with more virtual functions without breaking binary compatibility with applications built for the previous version of the library.
One option would be to use the PImpl idiom to hide all the classes having virtual functions, but that also seem to have it's limitations: this way applications lose the possibility of subclassing the classes of the library and overriding the virtual methods.
How would you design a API class which can be subclassed in an application, without losing the possibility to extend the API with (not abstract) virtual methods in a new version of the dll while staying backward binary compatible?
Update: the target platforms for the library are windows/msvc and linux/gcc.
| Several months ago I wrote an article called "Binary Compatibility of Shared Libraries Implemented in C++ on GNU/Linux Systems" [pdf]. While concepts are similar on Windows system, I'm sure they're not exactly the same. But having read the article you can get a notion on what's going on at C++ binary level that has anything to do with compatibility.
By the way, GCC application binary interface is summarized in a standard document draft "Itanium ABI", so you'll have a formal ground for a coding standard you choose.
Just for a quick example: in GCC you can extend a class with more virtual functions, if no other class inherits it. Read the article for better set of rules.
But anyway, rules are sometimes way too complex to understand. So you might be interested in a tool that verifies compatibility of two given versions: abi-compliance-checker for Linux.
|
1,774,920 | 1,775,035 | Can I use a shared library compiled on Ubuntu on a Redhat Linux machine? | I have compiled a shared library on my Ubuntu 9.10 desktop. I want to send the shared lib to a co-developer who has a Red Hat Enterprise 5 box.
Can he use my shared lib on his machine?
| First point: all of the answers regarding compiler version seem misguided. What's important are the linkages (and the architecture, of course).
If you copy the .so file over to the start system (into its own /usr/local/* or /opt/* directory, for example) then try to run the intended executable using an LD_PRELOAD environment settings. If the linker (ld-linux.so) manages to resolve all the symbols between the two then the program should load and run.
So it should be possible, and reasonably safe (so long as you're not over-writing any of the existing system libraries and just using LD_* /etc/ld.so.preload (in a chroot?) magic to link the target executables to this library.
However, I think it's a bad idea. You have a package management issue. Both Ubuntu and Red Hat have fine package management tools. Use them! (Note the proper place to ask questions about package management would be ServerFault or SuperUser, definitely not SO).
|
1,775,216 | 1,775,231 | SIGINT handling and getline | I wrote this simple program:
void sig_ha(int signum)
{
cout<<"received SIGINT\n";
}
int main()
{
string name;
struct sigaction newact, old;
newact.sa_handler = sig_ha;
sigemptyset(&newact.sa_mask);
newact.sa_flags = 0;
sigaction(SIGINT,&newact,&old);
for (int i=0;i<5;i++)
{
cout<<"Enter text: ";
getline(cin,name);
if (name!="")
cout<<"Text entered: "<<name;
cout<<endl;
}
return 0;
}
If I hit Ctrl+C while the program waits for input I get the following output:
Enter text: received SIGINT
Enter text:
Enter text:
Enter text:
Enter text:
(the program continues the loop without waiting for input)
What should I do?
| Try adding the following immediately before your cout statement:
cin.clear(); // Clear flags
cin.ignore(); // Ignore next input (= Ctr+C)
|
1,775,573 | 1,775,590 | C++ programing error | I am new to C++ programming.
So I was trying my luck executing some small programs.
I am working on HP-UX which has a compiler whose
executable is named aCC.
I am trying to execute a small program
#include <iostream.h>
using namespace std;
class myclass {
public:
int i, j, k;
};
int main()
{
myclass a, b;
a.i = 100;
a.j = 4;
a.k = a.i * a.j;
b.k = 12;
cout << a.k << " " << b.k;
return 0;
}
When I compile this it gives me an error:
> aCC temp.cpp
Error 697: "temp.cpp", line 2 # Only namespace names are valid here.
using namespace std;
^^^
What exactly is the problem?
Is std not considered as a namespace in the aCC compiler or is there some serious drawback with aCC?
If I change the <iostream.h> to <iostream>, I get some more errors added as below.
>aCC temp.cpp
Error 112: "temp.cpp", line 1 # Include file <iostream> not found.
#include <iostream>
^^^^^^^^^^
Error 697: "temp.cpp", line 2 # Only namespace names are valid here.
using namespace std;
^^^
Error 172: "temp.cpp", line 14 # Undeclared variable 'cout'.
cout << a.k << " " << b.k;
| Which version of aCC are you using? Older versions used a pre-standard STL implemenntation that put everything in the global namespace (i.e. didn't use the std namespace)
You might also need to use the -AA option when compiling. This tells the compiler to use the newer 2.x version of HP's STL library.
>aCC -AA temp.cpp
And it should always be
<iostream>
<iostream.h>
is from a pre-standard implementation of the language, though it is usually shipped so as to maintain backwards compatibility with older code.
|
1,775,737 | 1,775,839 | How can I open a C++ or Java project S60 5th Edition SDK 1.0 with Netbeans | I installed S60 5th Edition SDK 1.0 but I can't open project on netbeans? How can this be done?
| for a java project, you need to install the Mobility plugin. go to the Tools/Plugins menu, and select Mobility in the Available plugins tab.
once you installed the plugin, you need to add the S60 SDK as a platform: go to the Tools/Java Platform menu and click on the Add platform button. In the dialog window which opens, select Java ME MIDP Platform Emulator and click Next. NetBeans will then search your system for an available platform. if the SDK has been properly installed, it will promptly be listed as an available platform to be added to NetBeans.
remember that the Nokia SDK have to be installed in a directory which name does not contain a space.
|
1,775,784 | 1,775,795 | Strange class behaviour when used inside a Qt app | I've a simple class with these, also simple, constructors:
audio::audio() {
channels = NULL;
nChannels = 0;
}
audio::audio(const char* filename) {
audio();
getFromFile(filename);
}
(Before it was audio():channels(NULL), nChannles(0), loaded(false){..., I'll say later why this changed...). The function getFromFile starts like this:
void audio::getFromFile(const char* filename) {
baseUtils::dynVec<float> *chans;
if (channels != NULL)
deleteChannels();
sox_format_t *in;
sox_sample_t buff[AUDIO_CLASS_READ_SAMPLES];
sox_sample_t sample;
...
As you can see, it checks if loaded is true and if it is runs some delete(s) on internal buffers. Of course, as you can see from the constructor, at first run loaded is false, then the 2nd constructor will call the first constructor and then have loaded = false.
If I run this class in a simple command line app, everything runs fine. But if I put it in a Qt application, precisely in a slot that does this:
void buttonPushed() {
QString s = QFileDialog::getOpenFileName();
std::cout << "file choosen: " << s.toStdString() << "\n";
sndfile = s.toStdString();
if (aud == NULL){
aud = new audio(sndfile.c_str());
ui.widget->setAudio(aud);
ui.widget->update();
}
[...]
it will have channels != NULL (after invoking the 2nd constructor) and try to delete a pointer that is not assigned (resulting in a segmentation fault). Using GDB I found that channels is set to some strange value, and nChannels too... This smells like a race condition, but apparently doesn't seem to be the case. I put a check in the slot to see if aud != NULL, to avoid this. Do you have any ideas? Why is it happening? I tried to use Valgrind and it says that at channels != NULL I am trying to do a conditional jump with an uninitialized value! How can it be? What about the constructors?
| The problem is in the audio::audio(const char* filename) constructor. The first statement is audio(); which I believe you are trying to call the default constructor. However, C++ doesn't allow one ctor to call another one. So you have uninitialized pointers. If you want to do something like this, write a private method called init() and call it from both the constructors. audio(); statement creates a temporary (unnamed) audio object using the default ctor which is destroyed immediately after this statement. So the object you are accessing after this is a different object which has uninitialized pointers.
|
1,775,822 | 1,776,178 | Out of memory on _beginthreadex |
I currently debug a multi threaded application, which runs without errors until some functions where called about 2000 times. After that the application stops responding, which I could track down to _beginthreadex failing with an out of memory error.
When examining the Application in ProcessExplorer I can see a growing number of thread handles leaked and a growing virtual memory until the error occurs, the private bytes stay low.
The leaked threads also call CoInitialize and never call CoUninitialize.
What I would like to know is:
What does the Virtual memory represent ?
Is the virtual memory related to the leaked thread handles?
Does COM or MSXML6 (called by the threads) copy thread handles and how can I Close them?
I hope that my question is clear and doesn't break any roules,it is my first question and english isn't my first language.:-(
I forgot to mention, I close the handles returned by _beginthreadex once the threads get terminated, which reduces the number of open handles by about half but does not affect the virtual memory.
Additionally before i inserted the CloseHandle call each thread handle shown in ProcessExplorer had a handle count of two for the thread.
Edit
I fell stupid for not including this before, I know that the threads exit as the number of active threads while debugging with visual studio does not grow. And I do hope that not all of the leaked memory is a result of calls
to TerminateThread as they are used in a rather big library and I would prefer not modifying that.
To the com part of my question, with !htrace -diff i find thread handles allocated by msxml but not freed after the functioncalls end, could they be related to the leak or will they be Closed at a later time?
Thanks for all those comments, while the problem is still there they helped me understand it better.
| The virtual memory available to a process is 2Gb of the 4Gb address space. Each Thread reserves about 1Mb of virtual memory space by default for its stack space. win32 applications therefore have a limit of about 2000 live threads before virtual memory becomes exhausted.
Virtual memory is the memory that applications get in modern virtual memory OS's like windows. What happens on Win32 is, your application gets given a 2Gb virtual address space. When your program calls new or malloc, after tunneling trhough several layers, space gets allocated for your application ON DISK - in the pagefile. When CPU instructions try to access that memory, hardware exceptions get thrown and the kernel allocates physical RAM to that area, and reads the contents from the pagefile.
So, regardless of the physical RAM in the PC, each and every application believes it has access to a whole 2Gb.
Virtual Memory is a count of how much of your 2Gb space has been used up.
Each thread (see above) reserves 1 Mb of virtual address space for its stack to grow. Most of that 1Mb is just reserved space (hopefully) without the backing of RAM or pagefile.
When you close a thread handle you do NOT close the thread. threads are terminated by another thread calling TerminateThread (which leaks the threads stack and some other resources so NEVER use it), calling ExitThread() themselves, or by exiting from their ThreadProc.
So, with the 2000 call limit, the unmatched CoInitialize and CoUninitialize calls, I would say that your threads are not exiting cleanly or at all. Each of the 2000 worker threads is stuck doing something rather than exiting after finishing their work.
|
1,776,174 | 1,776,313 | C++ new standard, technologies and more | I'm developing in C++ mainly.
i used to develop using VS 2005 with libraries like MFC , sometimes using COM. only on WIN platform.
as i took a break from programming for a year, I want to be able now to get acquainted with all the new features and technologies being used today with C++.
Is MFC still worth something today ? Are there any new GUI libraries developed by Microsoft to replace MFC ? is it worth studying the new C++Ox standard even though it was not released yet ?
basically , my question is which libraries/technologies should i learn that are worthwhile today in the competitive job market and at the same time aren't deprecated.
(and i mean using C++, learning new programming language is def not my main focus at the moment)
thanks
| There's a lot of MFC out there, and it isn't going away any time soon. It's still a quite viable way to get stuff done, and it's going to keep working for the foreseeable future.
That said, it's no longer the preferred framework from Microsoft, and third-party support (libraries and such) is dying off. If you are starting a new project, DON'T use MFC. Use whatever the current C# frameworks are, because that's what Microsoft is most interested in right now, and thus, it's what's getting the most support.
As for libraries, definitely learn about the Boost libraries if you are going to be doing more C++ - there's a LOT of great stuff in there, and you'll get a lot more done with them, than without them.
|
1,776,291 | 1,776,301 | Function names in C++: Capitalize or not? | What's the convention for naming functions in C++?
I come from the Java environment so I usually name something like:
myFunction(...) {
}
I've seen mixed code in C++,
myFunction(....)
MyFunction(....)
Myfunction(....)
What's the correct way?
Also, is it the same for a class method as well as a non-class method?
| There isn't a 'correct way'. They're all syntactically correct, though there are some conventions. You could follow the Google style guide, although there are others out there.
From said guide:
Regular functions have mixed case; accessors and mutators match the name of the variable: MyExcitingFunction(), MyExcitingMethod(), my_exciting_member_variable(), set_my_exciting_member_variable().
|
1,776,372 | 1,781,820 | Custom painting QMainWindow title bar | Does anybody know how can I customize title bar of a main window in QT? I would like to make some custom painting over the "normal" drawing.
The QT version I'm interested in is 4.5 or 4.6 (beta)
| Actually, the title bar is a part of what the "window manager" adds. This could be Windows, OS X or whatever you are running in your X11 environment. Either way, you need to remove the bar and replace it with one of your own. To do this, use the Qt::WindowFlags (http://doc.qt.digia.com/4.5/qt.html#WindowType-enum) to make the titlebar go away. This does, however, make your application sensitive to platforms and, on X11, window manager. You can only hint that you want to have a window without a titlebar...
|
1,776,384 | 1,783,038 | How can I add widgets to title bars in QMainWindow? | Is any posibility to add widgets in titlebar of QMainWindow?
I try to avoid "emulate" a title bar by making a custom widget for that and hiding the default title bar (from Qt::WindowFlags).
I am using QT 4.5 or 4.6 beta.
| You cannot. What you can do is to create a completely custom window by hinting that you don't want a title bar using a Qt::WindowFlag. Notice - these flags are hints and not settings. Then you can create your own title bar and add whatever you like to it.
Also, notice, this will make your application harder to move between platforms. On the X11 side, you will even have to test against different window managers as they sometimes treat hints differently.
|
1,776,399 | 1,776,421 | What are the trade-offs between procedurally copying a file versus using ShellExecute and cp? | There are at least two methods for copying a file in C/C++: procedurally and using ShellExecute. I can post an explanation of each if needed but I'm going to assume that these methods are known. Is there an advantage to using one method over the other?
| Procedurally will give you better error checking/reporting and will work cross-platform -- ShellExecute is Windows API only.
You could also use a third-party filesystem library to make the task less annoying -- boost::filesystem is a good choice.
|
1,776,491 | 1,776,498 | Question on C++ Timers | I am currently working on a project that will act like a Online selling website such as Amazon, or Ebay in a very small scale. I was wondering if anyone could point me in the right direction on how to use Timers for C++. Learning Socket Programming at the moment, and was trying to incorporate the timer for the auction time when someone is selling their product.
Thanks
| You mean like timer_create?
How are you handling your sockets? Threads or select? If the latter (or something like select), timer_create will be a natural fit.
|
1,776,634 | 1,778,461 | Design and Readbility | I am working on a project written in C++ which involves modification of existing code. The code uses object oriented principles(design patterns) heavily and also complicated stuff like smart pointers.
While trying to understand the code using gdb,I had to be very careful about the various polymorphic functions being called by the various subclasses.
Everyone knows that the intent of using design patterns and other complicated stuff in your code is to make it more reusable i.e maintainable but I personally feel that, it is much easier to understand and debug a procedure oriented code as you definitely know which function will actually be called.
Any insights or tips to handle such situations is greatly appreciated.
P.S: I am relatively less experienced with OOP and large projects.
| gdb is not a tool for understanding code, it is a low-level debugging tool. Especially when using C++ as a higher level language on a larger project, it's not going to be easy to get the big picture from stepping through code in a debugger.
If you consider smart pointers and design patterns to be 'complicated stuff' then I respectfully suggest that you study their use until they don't seem complicated. They should be used to make things simpler, not more complex.
While procedural code may be simple to understand in the small, using object oriented design principals can provide the abstractions required to build a very large project without it turning into unmaintainable spaghetti.
For large projects, reading code is a much more important skill than operating a debugger. If a function is operating on a polymorphic base class then you need to read the code and understand what abstract operations it is performing. If there is an issue with a derived class' behaviour, then you need to look at the overrides to see if these are consistent with the base class contract.
If and only if you have a specific question about a specific circumstance that the debugger can answer should you step through code in a debugger. Questions might be something like 'Is this overriden function being called?'. This can be answered by putting a breakpoint in the overriden function and stepping over the call which you believe should be calling the overriden function to see if the breakpoint is hit.
|
1,776,636 | 1,776,782 | C++ overloading operator= in template | Hi all I'm having trouble with C++ template operator=
What I'm trying to do:
I'm working on a graph algorithm project using cuda and we have several different formats for benchmarking graphs. Also, I'm not entirely sure what type we'll end up using for the individual elements of a graph.
My goal is to have a templated graph class and a number of other classes, each of which will know how to load a particular format. Everything seems to work alright except the point where the graphCreator class returns a graph type from the generate function.
Here is my code:
Graph opertator=:
MatrixGraph<T>& operator=(MatrixGraph<T>& rhs)
{
width = rhs.width;
height = rhs.height;
pGraph = rhs.pGraph;
pitch = rhs.pitch;
sizeOfGraph = rhs.sizeOfGraph;
rhs.Reset();
}
the rhs.reset() call removes all references to allocated memory so they will not be deallocated by rhs. Only one graph is allowed to have a reference to the allocated graph memory.
Graph copy constructor:
MatrixGraph(MatrixGraph<T>& graph)
{
(*this) = graph;
}
Graph Creator load function:
MatrixGraph<T> LoadDIMACSGraphFile(std::istream& dimacsFile)
{
char inputType;
std::string input;
GetNumberOfNodesAndEdges(dimacsFile, nodes, edges);
MatrixGraph<T> myNewMatrixGraph(nodes);
while(dimacsFile >> inputType)
{
switch(inputType)
{
case 'e':
int w,v;
dimacsFile >> w >> v;
myNewMatrixGraph[w - 1][v - 1] = 1;
myNewMatrixGraph[v - 1][w - 1] = 1;
break;
default:
std::getline(dimacsFile, input);
break;
}
}
return myNewMatrixGraph;
}
And finally in main.cpp where I'm trying to unit test this I use it:
DIMACSGraphCreator<short> creator;
myGraph = creator.LoadDIMACSGraphFile(instream);
When I try to compile I get this error:
main.cpp: In function 'int main(int, char**)':
main.cpp:31: error: no match for 'operator=' in 'myGraph = DIMACSGraphCreator<T>::LoadDIMACSGraphFile(std::istream&) [with T = short int](((std::istream&)(& instream.std::basic_ifstream<char, std::char_traits<char> >::<anonymous>)))'
MatrixGraph.h:103: note: candidates are: MatrixGraph<T>& MatrixGraph<T>::operator=(MatrixGraph<T>&) [with T = short int]
make: *** [matrixTest] Error 1
| The problem is you're returning by value (correctly) but trying to bind that temporary object to a non-const reference (for the op= parameter). You can't do this.
The solution is to change things around, which can result in non-idiomatic code; use an auto_ptr_ref-like construct, which gets around this in a fairly bad-but-encapsulated way; or use r-value references, which are designed for exactly this situation. However, r-value references are only available as part of C++0x, and your compiler may not support them yet.
Make sure to return *this in your op= as well. Without warnings turned on your compiler may silently (and against the standard) accept that function without a return statement. (I don't know why.)
Example of the first solution:
// move return value into output-parameter:
void LoadDIMACSGraphFile(std::istream& dimacsFile, MatrixGraph<T>& dest);
// ...
DIMACSGraphCreator<short> creator;
creator.LoadDIMACSGraphFile(instream, myGraph);
std::auto_ptr is in the the stdlib, and uses a special "holder" class named auto_ptr_ref to implement move semantics.
|
1,776,641 | 1,776,659 | How do I apply the DRY principle to iterators in C++? (iterator, const_iterator, reverse_iterator, const_reverse_iterator) | OK, so I have two (completely unrelated, different project) classes using iterators now. One has iterator and reverse_iterator working as intended, and the other, current one has iterator and a semi-broken const_iterator (specifically, because const_iterator derives from iterator, the code LinkedList<int>::iterator i = const_list.begin() is valid and allows you to modify the const defined list...).
I intend to add all four types to this class... If I can.
How would I proceed to minimize copy/pasting code and changing only the return type? Create a base class like base_iterator to inherit from? Create an iterator or const_iterator and inherit from that? Inherit from some std:: class? If any of these cases are the "best" approach, what code goes where?
Perhaps none of the alternatives are good? I'm quite lost here, and can't find much reference material.
Any advice is appreciated, but please keep in mind that I'm new to the subject (both iterators and C++ in general, especially OOP). I've tried, in vain, to study the header files shipped with GCC - they're not exactly the tutorial I'm looking for.
| Sometimes, blanket application of the so-called DRY rule (Don't Repeat Yourself, for those who aren't familiar) is not the best approach. Especially if you're new to the language (C++ and iterators) and OOP itself (methodology), there's little benefit in trying to minimise the amount of code you need to write right now.
I would implement the two iterators using appropriate code for each of them. Perhaps after you have more experience with the language, tools, and techniques, then go back and see whether you can reduce the amount of code by factoring out common code.
|
1,776,961 | 1,784,986 | Finite State Machine program | I am tasked with creating a small program that can read in the definition of a FSM from input, read some strings from input and determine if those strings are accepted by the FSM based on the definition. I need to write this in either C, C++ or Java. I've scoured the net for ideas on how to get started, but the best I could find was a Wikipedia article on Automata-based programming. The C example provided seems to be using an enumerated list to define the states, that's fine if the states are hard coded in advance. Again, I need to be able to actually read the number of states and the definition of what each state is supposed to do. Any suggestions are appreciated.
UPDATE:
I can make the alphabet small (e.g. { a b }) and adopt other conventions such as the
start state is always state 0. I'm allowed to impose reasonable restrictions on the number of
states, e.g. no more than 10.
Question summary:
How do I implement an FSA?
| First, get a list of all the states (N of them), and a list of all the symbols (M of them). Then there are 2 ways to go, interpretation or code-generation:
Interpretation. Make an NxM matrix, where each element of the matrix is filled in with the corresponding destination state number, or -1 if there is none. Then just have an initial state variable and start processing input. If you get to state -1, you fail. If you run out of input symbols without getting to the success state, you fail. Otherwise you succeed.
Code generation. Print out a program in C or your favorite compiler language. It should have an integer state variable initialized to the start state. It should have a for loop over the input characters, containing a switch on the state variable. You should have one case per state, and at each case, have a switch statement on the current character that changes the state variable.
If you want something even faster than 2, and that is sure to get you flunked (!), get rid of the state variable and instead use goto :-) If you flunk, you can comfort yourself in the knowledge that that's what compilers do.
P.S. You could get your F changed to an A if you recognize loops etc. in the state diagram and print out corresponding while and if statements, rather than using goto.
|
1,776,971 | 1,776,982 | How should I handle Inconsistent Objects in C++? | Say, I want to create a File class
class File{
public:
File(const char *file){
openFile(file);
}
~File();
isEmpty();
};
openFile checks if the file exists or if the contents of the file are valid or not.
File *file = new File("filepath");
if(file)
file->isEmpty();
if my filepath is correct, then all fine, file instance is proper and we can invoke file->isEmpty();
What is the file does not exist, in that case still the check if(file) evaluates to true and will lead to creation of file instance which is actually invalid. How can i guarantee that if file path is invalid, the file instance should be null.
| Your constructor should throw an exception in the case that the file couldn't be opened.
File::File( const char* pPath )
{
if ( !openFile( pPath ) )
throw FileNotFound( pPath );
}
|
1,776,993 | 1,777,052 | C++ collection of abstract base classes | how can I create STL collection of classes which implement abstract base class using the base class as collection value, without using pointers?
is there something in Boost that allows me to implement it? The collection specifically is map.
Thanks
| You cannot avoid pointers completely. You must store pointers in the collection if you want to avoid Object slicing. Boost has a container that hides the pointers pretty well: ptr_map
|
1,777,060 | 1,777,064 | What Linux Full Text Indexing Tool Has A Good C++ API? | I'm looking to add full text indexing to a Linux desktop application written in C++. I am thinking that the easiest way to do this would be to call an existing library or utility. This article reviews various open source utilities available for the Gnome and KDE desktops; metatracker, recoll and stigi are all written in C++ so they each seem reasonable. But I cannot find any notable documentation on how to use them as libraries or through an API. I could, instead, use something like Clucene or Xapian, which are generic full text indexing libraries. They seem more straightforward but if I used them, I'd have to implement my own indexing daemon, an unappealing prospect.
Also, Xesam seems to be the latest thing, does anyone have any evidence that it works?
So, does anyone have experience using any of the applications or libraries? How did you use it and what documentation was useful?
| I used CLucene, which you mentioned (and also Lucene.NET), and found it to be pretty good.
|
1,777,308 | 1,777,346 | What does this code-snippet do? | Question:
Given the following code snippet:
bool foo(int n) {
for(int i=3;i<sqrt(n)+0.5;i+=2)
{
if((n%i)==0){
return false;
}
}
return true;
}
Can you figure out what is the purpose of the function foo ?
Well,On first look it may seems that foo is checking for prime numbers but it is not the case.I wrote a small test program and got this output:
foo returns true for these numbers between 1 to 100:
1 2 3 4 5 6 7 8 10 11 13 14 16 17 19 20 22 23 26 28 29 31 32 34 37 38 41 43 44 4
6 47 52 53 58 59 61 62 64 67 68 71 73 74 76 79 82 83 86 88 89 92 94 97
foo returns false for these numbers between 1 to 100:
9 12 15 18 21 24 25 27 30 33 35 36 39 40 42 45 48 49 50 51 54 55 56 57 60 63 65
66 69 70 72 75 77 78 80 81 84 85 87 90 91 93 95 96 98 99 100
I am unable to understand what the foo is doing from the series.
| It looks like a prime number checker that doesn't deal with even numbers or one, i.e. it assumes that you've already discarded even numbers and one.
The numbers for which it returns true are primes, or some non-primes that consist of powers of two multiplied by at most one other prime. The non-primes that it returns true for are those with no odd prime divisors or where the only odd prime divisor is larger than the square root of the original number.
Have a look at a list of numbers for which n % 2 && foo(n).
|
1,777,367 | 1,777,626 | Display a month not as the number 1 | I am having trouble trying to figure out how i would display a month without having to display "January" like in my switch - if i try to just oputput it i get a number 1
Do i need to create memory for the date priceDate; private member?
than copy in my copy constructor?
sorry about formatting. i had to move stuff over so it would display on this page properly
This is what i have. Do i need to create memory for the private member date?
class date
{
public:
typedef enum {INVALID, JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER}
Month;
date(Month month, int day, int year);
date(const date& date); // copy constructor
date(void); // default constructor
~date(void);
friend ostream& operator<<(ostream& out, const date& d);
private:
Month month;
int day;
int year;
};
also.
class stock
{
public:
stock(char const * const symbol, char const * const name, int sharePrice, date priceDate);
// sharePrice is given as a number of CENTS
stock(const stock& s); // copy constructor
stock(void); // default constructor
char const * const getSymbol(void) const;
stock& operator=(const stock& s);
stock& operator=(stock const * const s);
~stock(void);
// display column headers
static void displayHeaders(ostream& out); // display the headers when this instance is printed
// prints share price as DOLLARS
// (e.g. 2483 would print out as 24.83 and 200 would print out as 2.00)
friend ostream& operator<<(ostream& out, const stock& s);
friend class hashmap;
private:
int sharePrice;
char* name;
char* symbol;
date priceDate;
int removed;
};
now the functions.
date::date(Month month, int day, int year)
{
this->day = day;
this->month = month;
this->year = year;
}
/**
* date: copy constructor
* in: date
* out: out
* return: none
**/
date::date(const date& date):day(date.day),month(date.month),year(date.year)
{
}
date::date()
{
day = 0;
year = 0;
month = INVALID;
}
date::~date(void)
{
}
ostream& operator<<(ostream& out, const date& d)
{
switch(d.month)
{
case 1: out << "January " << d.day <<", " << d.year;
break;
case 2: out << "Febuary "<< d.day <<", " << d.year;
break;
case 3: out << "March "<< d.day <<", " << d.year;
break;
case 4: out << "April "<< d.day <<", " << d.year;
break;
case 5: out << "May "<< d.day <<", " << d.year;
break;
case 6: out << "June "<< d.day <<", " << d.year;
break;
case 7: out << "July " << d.day <<", " << d.year;
break;
case 8: out << "august "<< d.day <<", " << d.year;
break;
case 9: out << "September "<< d.day <<", " << d.year;
break;
case 10: out << "October "<< d.day <<", " << d.year;
break;
case 11: out << "November "<< d.day <<", " << d.year;
break;
case 12: out << "december "<< d.day <<", " << d.year;
break;
}
return out;
}
| Enums are just numbers. If you want an enum value to correspond with a string, then you need to create a mapping of some sorts, for example:
const char * asString(Month month)
{
static const char * cMonths[] = { "January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December" };
return cMonths[static_cast<int>(month) - 1];
}
Do i need to create memory for the
private member date?
date priceDate;
This code is ok. The runtime will allocate the required memory on the stack for you.
|
1,777,486 | 1,777,677 | Function Pointers in Objective C | Quick question. Does anyone know how to get the function pointer of an objective c method?
I can declare a C++ method as a function pointer, but this is a callback method so that C++ method would need to be part of the class SO THAT IT CAN ACCESS THE INSTANCE FIELDS. I don't know how to make a C++ method part of an objective c class. Any suggestions?
| Typically, you need two pieces of information to call back into Objective-C; the method to be invoked and the object to invoke it upon. Neither just a selector or just the IMP -- the instanceMethodForSelector: result -- will be enough information.
Most callback APIs provide a context pointer that is treated as an opaque value that is passed through to the callback. This is the key to your conundrum.
I.e. if you have a callback function that is declared as:
typedef void (*CallBackFuncType)(int something, char *else, void *context);
And some API that consumes a pointer of said callback function type:
void APIThatWillCallBack(int f1, int f2, CallBackFuncType callback, void *context);
Then you would implement your callback something like this:
void MyCallbackDude(int a, char *b, void *context) {
[((MyCallbackObjectClass*)context) myMethodThatTakesSomething: a else: b];
}
And then you would call the API something akin to this:
MyCallbackObjectClass *callbackContext = [MyCallbackObjectClass new];
APIThatWillCallBack(17, 42, MyCallbackDude, (void*)callbackContext);
If you need to switch between different selectors, I would recommend creating a little glue class that sits between the callback and the Objective-C API. The instance of the glue class could contain the configuration necessary or logic necessary to switch between selectors based on the incoming callback data.
|
1,777,553 | 6,755,651 | G++ Compilers for MonoDevelop | How do you setup a G++ compiler for MonoDevelop?
On both OS X and Windows Vista the default install complains about "Compiler Not Found: g++".
Is MonoDevelop not a good cross platform IDE for C++ development (since it is a C#/Java IDE).
Thanks SO!
| I would say it is not.
C# and C++ are 2 different worlds.
My suggestion: If you want to write xplatform apps in C++, get familiar with either wxWidgets or QT.
wxWidgets has a more liberal license though and does not need a metacompiler. In the newest release it makes also use of the STL, if the compiler supports it.
|
1,777,639 | 1,777,647 | How to test a byte against a hex value? | I want to test if the byte I read from a data file is 0xEE, what should I do? I tried if (aChar == 0xEE) but doesn't seems working.
| When reading a signed char, the value will never be 0xEE. IE:
#include <stdio.h>
int main()
{
char c = 0xEE; // assumes your implementation defines char as signed char
// c is now -18
if (c == 0xEE)
{
printf("Char c is 0xEE");
}
else
{
printf("Char c is NOT 0xEE");
}
}
The output will be
Char c is NOT 0xEE
When the signed character is read, the value will range from -0x7F to 0x80. An unsigned char is interpreted from 0x00 up to 0xFF, and is typically what you want for "raw" bytes.
Change:
char aChar;
to
unsigned char aChar;
and it should work.
|
1,777,717 | 1,796,246 | Is this a fine std::auto_ptr<> use case? | Please suppose I have a function that accepts a pointer as a parameter. This function can throw an exception, as it uses std::vector<>::push_back() to manage the lifecycle of this pointer. If I declare it like this:
void manage(T *ptr);
and call it like this:
manage(new T());
if it throws an exception pushing the pointer into the std::vector<>, I effectively have got a memory leak, haven't I?
Would declaring the function like this:
void manage(std::auto_ptr<T> ptr);
solve my problem?
I would expect it to first allocate the std::auto_ptr on the stack (something that I guess couldn't ever throw an exception) and let it acquire ownership over the pointer. Safe.
Then, inside the function, I would push the raw pointer into the std::vector<>, which is also safe: if this fails, the pointer will not be added, but the smart pointer will still be owning the pointer so it will be destroyed. If the pushing succeeds, I would remove the smart pointer's ownership over that pointer and return: this can't throw an exception, so it will always be fine.
Are my theories correct?
-- Edit --
No, I think I can't do that. Doing that would require taking a non-const reference to rvalue (to take away ownership from the smart pointer). I would have to write
std::auto_ptr<T> ptr(new T());
manage(ptr);
for that to work, something that's quite inconvient in my case. I'm writing this so that I can implement RAII without polluting much the code. Doing that thing would not help, then. That would be catch 22.
-- Edit 2 --
Pulling what Jason Orendorff said down there here for quick reference by readers, the ultimate solution seems to be the following:
void manage(T *ptr)
{
std::auto_ptr<T> autoPtr(ptr);
vector.push_back(ptr);
autoPtr.release();
}
This solves the problem of the useless non-const reference to rvalue.
When I finish this class I'm coding I'll post it back here in case anyone finds it useful.
-- Edit 3 --
Ok, there has been a lot of discussion here, and there are key points that I should have clarified before. In general, when I post at stackoverflow, I try to explain the reason behind my questions and, in general, that is completely useless. So this time I thought I should go straight to the point. Turns out it didn't work quite well XD
Unfortunately my brain is deadlocking now, so I think I won't even be able to explain correctly what I first thought to accomplish my goals. I am trying to find a good solution for atomic operations and exception-safe code writing that fits lots of cases, but really, I can't handle it XD I think this is the kind of thing I will only master with time.
I am a really new C++ programmer and my focus is game development. When an exception is thrown in a game engine, it is the end of execution. The system will free all the memory for my process, so it doesn't really matter if one or two pointers leak here and there. Now that I am developing a server application, I'm finding it hard to deal with exceptions, because an exception can't crash the server; it must "crash the request".
That is, "Well, client, unfortunately the developers didn't foresee this condition, so you'll have to try it later (up to here, it is basically the same thing as with a game engine, nothing is being repared, only it is isolated to the context of just a request, and not the whole process). But don't panic, as everything was left in a valid state (here is one of the differences, however. The process isn't terminated, so the operating system can't free the resources for you; furthermore, you have to pay attention to undo the operations so far, so that you don't lock completely an user's account, for example, or even a full service provided by the server).".
I will just code more and more and note down my problems so that I can write a better question next time. I wasn't prepared to ask this now, I'm really sorry.
Thanks a lot for your replies, I really like stackoverflow. It is absolutely amazing how fast my questions are answered and how enlightening your answers are. Thanks.
| I think enough discussion has been generated to warrant yet another answer.
Firstly, to answer the actual question, yes, it is absolutely appropriate (and even necessary!) to pass an argument by smart pointer when ownership transfer occurs. Passing by a smart pointer is a common idiom to accomplish that.
void manage(std::auto_ptr<T> t) {
...
}
...
// The reader of this code clearly sees ownership transfer.
std::auto_ptr<T> t(new T);
manage(t);
Now, there is a very good reason why all smart pointers have explicit constructors. Consider the following function (mentally replace std::auto_ptr with boost::shared_ptr if it tickles your fancy):
void func(std::auto_ptr<Widget> w, const Gizmo& g) {
...
}
If std::auto_ptr had an implicit constructor, suddenly this code would compile:
func(new Widget(), gizmo);
What's wrong with it? Taking almost directly from "Effective C++", Item 17:
func(new Widget(), a_function_that_throws());
Because in C++ order of argument evaluation is undefined, you can very well have arguments evaluated in the following order: new Widget(), a_function_that_throws(), std::auto_ptr constructor. If a function throws, you have a leak.
Therefore all resources that will be released need to be wrapped upon construction in RAII classes before being passed into a function. This means all smart pointer have to be constructed before passing them as an argument to a function. Making smart pointers be copy-constructible with a const reference or implicitly-constructible would encourage unsafe code. Explicit construction enforces safer code.
Now, why shouldn't you do something like this?
void manage(T *ptr)
{
std::auto_ptr<T> autoPtr(ptr);
vector.push_back(ptr);
autoPtr.release();
}
As already mentioned, the interface idioms tell me that I can pass a pointer that I own and I get to delete it. So, nothing stops me from doing this:
T item;
manage(&t);
// or
manage(&t_class_member);
Which is disastrous, of course. But you'd say "of course I know what the interface means, I'd never use it that way". However you may want to add an extra argument to a function later. Or someone (not you, or you 3 years later) comes along this code, they may not see it the same way as you do.
This hypothetical "someone else" may only see a header without a comment and (rightly) presume the lack of ownership transfer.
They may see how this function is used in some other code and replicate the usage without looking at the header.
They may use code auto-completion to invoke a function and not read the comment or the function and presume the lack of ownership transfer.
They may write a function that wraps you manage function and yet someone else will use the wrapper function and will miss the documentation of the original function.
They may try to "extend" you code so that all the old code compiles (and automatically becomes unsafe):
void manage(T *t, const std::string tag = some_function_that_throws());
As you can see, explicit construction of a smart pointer makes it much harder to write unsafe code in the above cases.
Therefore, I would not recommend going against decades of C++ expertise to make perceivably "nicer" and "fun" API.
My 2c.
|
1,777,730 | 1,777,761 | Learning c++ from a C# background | I want to learn c++ as I will be working on image recognition, etc.
I have a few years solid experience in C# and I have made stuff with C# so I'm not lacking experience. What is a good book which will help me make the transition (I will still be doing C# as it is my main skill)?
Also, would you agree that to be good at C++, a lot of experience and being proficient in C# will help? As C++ is harder...
Thanks
|
Also, would you agree that to be good
at C++, a lot of experience and being
proficient in C# will help? As C++ is
harder...
Yes I agree with that. A lot of experience in development in any language helps in my opinion. With experience comes appreciation of best practices. Those practices may be different, but you will not dismiss them outright because you know (from your experience) that they are usually good for you.
Good book... Get "C++ primer" with "Effective (and more effective) C++" and you will be all set. Then if you need STL get yourself Josuttis and "Effective STL". Good luck
|
1,777,752 | 1,777,817 | Python importing & using cdll (with a linux .so file) | After one of my last questions about python&c++ integration i was told to use dlls at windows.
(Previous question)
That worked ok doing:
cl /LD A.cpp B.cpp C.pp
in windows enviroment, after setting the include path for boost, cryptopp sources and cryptopp libraries.
Now i'm tryting to do the same in linux, creating a .so file to import through ctypes on python2.5.
I did:
gcc -Wall -Wextra -pedantic A.cpp B.cpp C.cpp /usr/lib/libcryptopp.so -shared -o /test/decoding.so
and the so object is created ok. If removed "-shared" compilation is OK but stops as no main in there (obviously ;) ). Of course libcryptopp.so exists too.
But when i go to python and import the "so" file, it said that the attribute has no object "decrypt", "encrypt" or whatever i put there. using "dir" over the dll objects confirms that they are not there.
external functions are defined in A.cpp as:
int encrypt (params...)
//..
return num;
int decrypt (params...)
//..
return num;
also tried using:
extern "C" encrypt (params...)
.....
Could anyone tell me what i'm doing wrong?
Thanks in advance!
Rag
| C++ compiler mangles names of functions. To do what you are trying to do you must have the declaration prototype inside
extern "C" {...}
it's hard to tell from your samples what exactly you have in a source file.
As someone already mentioned, use nm utility to see what objects that are in your shared object.
Do not compile your object without -shared. Python load library does not support statically linked objects as far as am aware.
compile your object with g++ compiler instead, it will link to standard C++ Library, gcc does not.
|
1,777,855 | 1,777,860 | Trying to visualize points on a graph: how can I make C++ output this? | I am trying to create a simple visualization of what my code does. I am making a Poisson-Disk-Distribution class to generate a set of random points in a bounded rectangular region. Basically, what it does is it randomly generates a specified number of points in the bounded region and makes sure that each point is at least a certain distance away from all the other points. The random points will be used later to generate a random maze.
I am finished coding, but I want to perform a quick visual check of whether or not it works. I want to output the points as text on the console. Every point generated has an X-value and a Y-value, so I was hoping that I could output the generated points in the console by somehow marking an x wherever a point may lie.
For example, if I were to have a bounding rectangle of width and height of 4, and the points p1 = (0, 0) and p2 = (2, 2) it could output the following:
----
--x-
----
x---
Where - are empty spaces on the graph and x are the points p1 and p2.
So, I'm kind of stumped as to how to code this printing function. It sounds simple in my head, but I can't seem to implement it.
Oh, I tagged this as homework, but its not really part of my project. I just wanted to check if my code is actually working properly by implementing this quick (well, not so quick for me) function. Any hints/suggestions/solutions are welcome.
Thank you!
--
Edit:
The "points" are Point objects that hold two integer values for their x and y coordinates
The poisson-disk-generator generates a specified number of Point objects and places them in a list
| Assuming your data structure is a list of (x,y) pairs, a simple printing function could be:
for each row
for each column in current row
if the pair (col,row) exists in the list of (x,y) points
print "x"
else
print "-"
print newline
Since this has at least three nested loops, it's not the world's most efficient algorithm but it will be perfectly fast for any grid that you could reasonably print to the console. Improvements could be gained by pre-sorting the list of generated points and changing the searching algorithm, but you probably won't need to do that for now.
|
1,778,042 | 7,388,714 | Pop3 help for a C++ implementation! | Alright, so this is absolutely killing me... If anyone could help me, I would be the happiest man on the face of the earth...
So, I need to create a C++ email client for a project at school, and I've been using the POCO open source C++ library, and I've been fine for working with email servers that do not need SSL authentication, but anything that DOES require SSL, I've had no luck...
Here is the documentation for POCO: http://pocoproject.org/docs/
When you go there, you have to click on POCO:Net, and then in the bottom left frame, there is a bunch of documentation for different NET objects... I've particularly been using POP3ClientSession.
I've installed OpenSSL and compiled the library with SSL support, but nothing seems to work... I've also followed this tutorial:
http://pocoproject.org/wiki/index.php/NetSSL
If ANYONE has experience with POCO, or is just 1337 at SSL/C++, if you could help me get this working I would very much appreciate it! I've been working on this for the past 12 hours straight just to get SSL working, and have had 0 luck.
Well one of the things I'm not even quite sure about is if I compiled it with SSL correctly... I installed OpenSSH on my machine, and recompiled everything (took an hour!!!). I seemed to have everything compiled, but when I went to use it with the following include statement:
#include "Poco/Net/SecureStreamSocket.h"
Which is what the documentation told me to do, I got an error... They compiled in a folder called NetSSL_OpenSSL, so i took the headers and sources and copied them into the appropriate place in the Net folder, hoping for it to work. Afterwords I got another error:
fatal error C1083: Cannot open include file: 'Poco/Crypto/X509Certificate.h': No such file or directory I dont see Crypto anywhere...
But I do have the X509Certificate.h file... I even went as far as changing Crypto in the source to Net (because its the net folder that is now holding this file), but as I expect, that blew up in my face...
So, I guess the main question would be the following:
How can I send emails using POP3 with SSL sockets instead of the standard sockets used by the POP3ClientSession?
| As the error states
fatal error C1083: Cannot open include file: 'Poco/Crypto/X509Certificate.h'
This means it cant find the file, that is the only problem!!!
|
1,778,111 | 1,778,118 | What's the differences between .dll , .lib, .h files? | Why in a project should I include some *.lib, .h or some other files? And what are these things used for?
|
.h: header file, its a source file containing declarations (as opposed to .cpp, .cxx, etc. containing implementations),
.lib: static library may contain code or just links to a dynamic library. Either way it's compiled code that you link with your program. The static library is included in your .exe at link time.
.dll: dynamic library. Just like a static one but you need to deploy it with your .exe file because it's loaded at run time.
|
1,778,191 | 1,778,200 | Base Class Pointer to Hold Boost Enum | Currently, I am using a type-safe enum class from Boost Vault :
Which Typesafe Enum in C++ Are You Using?
I found it is difficult to have a parent class pointer to refer to all enum class, due to Boost::enum is a template class : boost::detail::enum_base<T>
I am using void fun(const boost::any& any), to accept any enum class. However, I need to cast them to an enum class before I perform iteration. I cannot cast to a base class boost::detail::enum_base<T>, as I do not have information on what T will be.
Any suggestion on how to solve this?
One of the requirement is that, the function argument must be in boost::any.
#include <iostream>
#include <boost/any.hpp>
#include "boost/enum.hpp"
// this macro
BOOST_ENUM(boolean,
(True)
(False)
)
// expands to this enum model
namespace expanded
{
class boolean : public boost::detail::enum_base<boolean>
{
public:
enum domain
{
False,
True,
};
BOOST_STATIC_CONSTANT(index_type, size = 2);
public:
boolean() {}
boolean(domain index) : boost::detail::enum_base<boolean>(index) {}
typedef boost::optional<boolean> optional;
static optional get_by_name(const char* str)
{
if(strcmp(str, "False") == 0) return optional(False);
if(strcmp(str, "True") == 0) return optional(True);
return optional();
}
private:
friend class boost::detail::enum_base<boolean>;
static const char* names(domain index)
{
BOOST_ASSERT(static_cast<index_type>(index) < size);
switch(index)
{
case False: return "False";
case True: return "True";
default: return "";
}
}
};
}
BOOST_ENUM(boolean2,
(True2)
(False2)
)
/* I want to have a function to accept any enum class. How? */
void fun(const boost::any& any)
{
/* How about boolean2 enum? How can I have a common pointer to point to enum class? */
const boolean* d = boost::any_cast<boolean *>(any);
/* I want to use unofficial boost::enum, because it allows me to iterate through enum's members. */
for (boolean::const_iterator iterator = d->begin(); iterator != d->end(); iterator++)
{
boolean x = *iterator;
std::cout<< "Iterate through enum : "<< x<< std::endl;
}
}
int main()
{
boolean b = boolean::True;
boolean2 b2 = boolean2::True2;
/* Assume until this stage, during runtime, I have no clue b is either boolean or boolean2. */
fun(&b);
/*
* Runtime error occur here.
* throw enable_current_exception(enable_error_info(e));
*/
fun(&b2);
getchar();
}
| If the access is not possible through the base class, use function templates:
template<class TE> // should be a boost enum
void fun(TE& en)
{
for (TE::const_iterator it = en.begin(); it != en.end(); ++it)
{
/* ... */
}
}
As for a common base pointer:
You can't use one the way the boost enum is defined. It doesn't have a single base class, instead it has seperate base classes per enum type and per (optional) value type.
Also, the main point of the boost enum is static type-safety - if what you're asking is meant to work on different enum types based on runtime-decisions you are using the wrong tool.
update:
If you really have that immutable requirements, you could base explicit casting on boost::any::type, e.g. (utilizing the function template given above):
const std::type_info& ti = any.type();
if(ti == typeid(boolean*)) {
fun(*boost::any_cast<boolean*>(any));
} else if(ti == typeid(boolean2*)) {
/* ... */
}
|
1,778,209 | 1,778,213 | suggest some online compiler for c/c++ | I am developing a website for which I need an online C/C++ compiler for testing code online.
Is there any possible and feasible solution for this?
I need this compiler so that students can test their code online.
| Codepad
For others languages too!
|
1,778,218 | 1,826,522 | Parser for 32-bit and 64-bit Mach-O binary/executable formats in C++ | I'm looking for a C++ library that can parse 32-bit and 64-bit Mach-O binary format. I don't need anything fancy, just a disassembly and splitting the file into its sections, so no decompilation, name demangling and so on.
I know I can either rip open any existing disassembler or craft my own binary parsers using the format specification from Apple, but I was kind of hoping not having to go that far, especially if someone else has done the work for me.
Many thanks!
| You can start with the open-source class-dump tool (http://www.codethecode.com/projects/class-dump/). It can read both 32 and 64 bits Mach-o binaries, and is known to have a decent parser.
|
1,778,245 | 1,778,258 | No Matching Function for Call to | In my object ' handler '
I have the following code:
Product tempProduct; // temporary Product storage variable
LINE481 tempProduct.setHandler(this);
Within my Product.h:
#include <string>
#include <qtimer.h>
#include "HandleTCPClient.h"
#ifndef PRODUCT_H
#define PRODUCT_H
class Handler;
//Define ourselves a product class
class Product
{
void startTimer();
public:
Product();
string seller, itemName, description, highestBidder;
double price, min, buyingPrice, currentBid;
int time;
bool isSold;
Handler handler();
void setHandler(Handler h);
public slots:
void setProductToSold();
};
#endif
For my Product.cpp:
#include <string>
using std::string;
#include "Product.h"
Product::Product()
{
seller = "";
itemName = "";
price = 0.00;
min = 0.00;
buyingPrice = 0.00;
time = 0;
description = "";
highestBidder = "None";
currentBid = 0.00;
}
void Product::setHandler(Handler h)
{
handler = h;
}
The issue I am having:
HandleTCPClient.cpp: In member function âint Handler::HandleTCPClient(int, std::string, std::string)â:
HandleTCPClient.cpp:481: error: no matching function for call to âProduct::setHandler(Handler* const)â
Product.h:34: note: candidates are: void Product::setHandler(Handler)
| You probably want to declare your setHandler function like this:
void Product::setHandler(Handler *h)
Also, inside the Product class, declare handler like this:
Handler *handler;
It looks like you might be more familiar with a language such as Java or Python that doesn't have an explicit pointer syntax. In C++, you must explicitly declare pointers using the * indication, otherwise the compiler will try to copy and pass around value objects (copying the whole object through its copy constructor).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.