I'm trying to make it so I have one object, that has a pointer, so multiple classes can work with the same object. But the only thing it's giving me is 1 instead of the hexadecimal address that I need.
My code:
code to create it:
SDL_Event event;
EventHandler eh(&event);
code using it:
EventHandler::EventHandler(SDL_Event* eventpointer)
{
EventHandler::event = eventpointer;
//This code is to test the pointer:
std::cout << &EventHandler::event << std::endl;
}
output:
1
Process returned 0 (0x0) execution time : 0.092 s
Try printing the value of event, not the address of it:
std::cout << EventHandler::event << std::endl;
There are actually several unusual things about your testcase. Correcting all of them, I end up with this:
EventHandler::EventHandler(SDL_Event* eventpointer) : event(eventpointer)
{
//This code is to test the pointer:
std::cout << event << "\n";
}
The things I changed are:
Prefer initialization lists to assigning values in constructor bodies
Print value of event variable not its address. The value of event is the same as the value of eventpointer, which is the same as the address of the original SDL_Event object.
Avoid the scope qualifier. Inside the class's functions, you may refer to members simply by name.
Aside: I'm going to answer the actual question in an aside since it turns out to be irrelevant to the author's true intent. The actual reason he sees 1 instead of a pointer value is this: he is trying to print the value of a pointer-to-member. operator<< has no overload which takes a pointer-to-member, so it converts it to bool instead. His expression is non-null, so the conversion results in true, which is printed as 1.
Related
I have the following program in which the private string mOutStr is filled with characters in method "FetchSessionStatus".
After that, if mOutStr is empty (aka: FetchSessionStatus doesn't fill it or some other error happened) mOutStr is replaced by a "default string" called mAliveMsg.
Finally mOutStr is passed by reference to method OnCommand. OnCommand writes the string inside a pipe and then should clear mOutStr. However, the clean never works: mOutStr remains filled.
void RtnodeSpvSession::EnqueueRead()
{
std::string sCmd;
FetchSessionStatus();
(mOutStr.empty()) ? sCmd = mAliveMsg : sCmd = boost::ref(mOutStr);
OnCommand(sCmd);
}
void RtnodeSpvSession::OnCommand(std::string& sCmd)
{
std::cout << "Sending message " << sCmd.c_str() << " of "<< sCmd.size() << " size\n";
write(fd[1], sCmd.c_str(), sCmd.size());
sCmd.clear();
}
//Simplified version of FetchSessionStatus
void RtnodeSpvSession::FetchSessionStatus()
{
mOutStr+="x";
}
The end result is that, cycle by cycle, mOutStr keeps increasing in size, which means sCmd.clear is not working (aka the pass by reference is not working) but I don't understand what I'm supposed to do.
Well the issue here is that you're not passing the string you think by reference.
In your case, boost::ref return a reference wrapper to mOutStr, however, when you assign it to sCmd, it'll copy the content of mOutStr into sCmd.
In your OnCommand function, sCmd is a reference to sCmd in RtnodeSpvSession::EnqueueRead, not to mOutCmd. If you want to clear mOutCmd, you have to either do it in EnqueueRead, or to actually pass it to the OnCommand function.
For clarification, reference_wrapper<T> offer an implicit conversion to T&, but std::string::operator=(const &str) does a copy of str into the left operand, and do not replace said operand.
Firstly please have a look at some simple codes that my questions derived from.
#include <iostream>
#include <string>
using namespace std;
string get_something()
{
cout << "output something";
return " and return something";
}
void print_something()
{
cout << "print something";
}
int main()
{
cout << get_something(); // will work
cout << print_something(); // will NOT work
return 0;
}
The only different thing I notice between get_something() and print_something() is that one is a return type and one isn't. As you can see I have added comments indicating that which one will work and not work.
However, I am really not sure what is happening behind the scene that makes it one possible and the other not possible.
I am not even sure how I should go about and search for this kind of question too.. so here I am asking a question.
Please enlighten me..
edit:
I am confused that how it is possible to do cout after cout..
both of the functions do that but one of them works and the other doesn't.
This seems to be a very common misunderstanding among beginners. Printing something via cout is not the same as returning a value from a function. Thats completely orthogonal things.
You can write:
std::string returned_value = get_something();
std::cout << returned_value;
But you cannot write:
??? returned_value = print_something();
std::cout << returned_value;
because print_something() does not return anything! void denotes the absence of a type. You cannot have an object of type void.
On the other hand, when you call a function, you can use the returned value (above), or you can ignore it, so this is correct code:
print_something(); // prints something
get_something(); // also print something and returned value is ignored
Note that the function get_something should get a better name, because it is not just "getting" a value. How about print_and_return_something()?
PS:
What I am really confused about is that, how is it possible to do a cout after a cout? Am I just missing what cout actually does?
Not sure If I understand, but I will try... std::cout is an object of type std::ostream. It has an operator<< that you can call, similar to calling methods of other objects. The following two are identical and just use different syntax:
std::cout.operator<<( "Hello World");
std::cout << "Hello World";
When you call print_something() then first the function is executed, then the return value is returned to the caller and execution continues with the caller. This:
std::cout << get_something();
is more or less the same as (well, its a crude simplification, but should be ok here):
// inside get_something
std::cout << "output something";
// return value
std::string result{"output something"};
// now execution continues in caller
std::cout << result;
Calling cout after cout is no different from calling some other function. Suppose you have a function print() that prints something then you can write
std::string print_and_return() {
std::string x{"Hello World"};
print(x);
return x;
}
The caller can do
std::string x = print_and_return(); // <- this already calls print()
print(x); // now we call it again
This is more or less the same as yours, just that I used some hypothetical print() instead of std::cout::operator<<.
Both your functions have a return type. It's just that one of them has a void return type.
The std::ostream class does not have an overload for << that takes a void type. This is sensible - what would be written to the stream in that case?
(cout is an instance of std::ostream that typically writes itself to the standard output which is normally the shell you're using to launch the program.)
Because print_something() has nothing to return, and cout want something to write to the console (the return value it is expecting). Therefore, it will give error.
get_something(), on the other hand, has something to return. So after executing it's rest of line (except return statement) it return the string, which gets printed by cout
get_something() returns something (what seems to be accepted by cout), so cout will receive the returned thing and will work.
On the other hand, print_something() returns nothing (because its return type is void), so cout cannot receive anything to print and won't work.
cout is a stream object.and we use << (insertion operator) to insert value like String,float,Int etc to it which will be displayed in output Screen.Since print_something() is not returning any value so nothing is inserted in stream ,That's why it is not working.
I recommend you to read about Streams in c++ ..
maybe this question will be a bit complicated and maybe i'm missing something of stupid.
I'll try to explain without any source code, because my project is big and i don't know how/where to start.
I have:
bool result = false;
bool* pointer = &result;
these variables are stored in some classes.. (not as in the above code).
When result is created, his address is something like 0x28fddc.
and the pointer variable takes this address.
Suddendly, without any reason (maybe), his address is not 0x28fddc anymore but something like 0x3a8c6e4.
With the pointer variable, i am trying to change the result var by doing:
*result = true;
But obviously, this doesn't work (and it doesn't give me any error). It will not change result var because it's in another address.
I don't know why this happens.
Can you only tell me how could this happen? And i'll try to fix.
(This classes are everytime being updated in some functions with parameters passed by reference).
For example:
void update_class(obj_class &obj);
(These names are only an example).
I hope i've been clear and if not, i'll just delete this topic.
Sorry for bad english but i'm italian :)
EDIT:
Now i'll try to provide some code..
button.h
class button
{
public:
void check_tap(SDL_Event* e);
bool* done;
}
messagebox.h:
class messagebox
{
public:
messagebox();
bool result_ok;
button btn_ok;
}
void check_tap(std::vector<messagebox> &msgbox, SDL_Event* e) {
for(unsigned int k=0; k<msgbox.size(); k++) {
msgbox[k].btn_ok.check_tap(e);
// check_tap is a function that i create for checking if the user is tapping the button with his finger or not. When the user presses the button and leaves it the done variable should become true, but result_ok seems not to be affected because his address here is different. This problem is only in this case using messagebox. I created more other buttons outside and all works perfect.
}
}
messagebox.cpp:
messagebox::messagebox() {
// Initializing things
btn_ok.done = &result_ok;
// Here, btn_ok.done gets the address of result_ok..
}
main.cpp:
std::vector<messagebox> msgbox;
msgbox.push_back(msgbox());
No, the address of variables do not change during their lifetime.
However, storing the address of a variable is problematical if the variable ceases to exist. A simple example is
#include <iostream>
int *p;
void f()
{
int i;
p = &i;
}
int main();
{
f();
std::cout << (void *)p << '\n';
// other code here
f();
std::cout << (void *)p << '\n';
}
In the above case, the two values of p may be the same, or they may differ. This is not because the address of variables change. It is because a variable, i is created each time f() is called, and ceases to exist when f() returns. The variable i in the first call of f() is, as far as your program is concerned, a distinct variable from i during the second call of f().
Depending on what happens with "other code here" in the above, the memory occupied by i in the first call of f() may be inaccessible (e.g. used for another variable) during the second call of f() - so, during the second call of f(), i will have a different address than during the first. There are no guarantees - you may also get lucky (or unlucky depending on how you look at it) and the addresses printed will be the same.
If you are getting behaviour that suggests, to you, that the address of a variable is changing then - somewhere in your code - there is a bug of some form. Typically, this will involve storing the address of a variable in a pointer, and using (or accessing the value of) the pointer after the variable ceases to exist. And any dereferrencing of that pointer (e.g. to access the variable pointed at) has undefined behaviour.
For example, any usage of *p like
*p = 42;
or
std::cout << *p << '\n';
in the main() I have given above will give undefined behaviour.
The act of assigning a pointer to contain the address of that variable does not change the lifetime of that variable.
Whenever I output a particular pointer address to std::cout, I get a crash:
bool MyClass::foo() const
{
std::cout << "this prints fine" << std::endl << std::flush;
std::cout << d << std::endl << std::flush; // crash!
return true;
}
Where d is a pointer member of the class, i.e.:
class MyClass {
// ...
private:
MyClassPrivate* d;
};
What could cause the application to crash? Even if it is a NULL pointer, or an initialized pointer, it should still print out the (perhaps invalid) address, right?
The application is compiled in debug mode, if that makes a difference. The function foo is not marked as inline.
Background: I am trying to track down a bug in an external application process. The bug is only caused when another application sends rapid-fire command to the process. I'm using std::cout to trace the execution of the external process.
If this is not a valid pointer, any access to a member field might cause an access violation. Non-virtual methods called on invalid pointers work just fine until they try to access a field, because the call itself doesn't need to dereference this.
For instance, this situation would crash roughly as you describe:
MyClass* instance = nullptr; // or NULL if you're not using C++11
instance->foo(); // will crash when `foo` tries to access `this->d`
There could be an overload of operator<<(ostream &, MyClassPrivate*), that dereferences the pointer. For example there certainly is if MyClassPrivate is really char.
Try std::cout << (void*)d;, see whether or not it makes a difference. If not, zneak's answer seems plausible.
For some reason when I try and read a property of a pointer to an object(GamePlayer) within an std::list (playerlist) it works at first, but when I try to access it later in another function I get a bunch of random numbers instead of the numbers for my client's socket. That was a mouthful, sorry. I hope someone could shed some light on the situation. I will include a simplified version of the defective code.
class GameRoom {
list<GamePlayer*> playerlist;
locigPort( LogicObj );
}
bool GameRoom::logicPort( LogicObj logit ) { // This is room[1]
list<GamePlayer*>::iterator it;
for (it = playerlist.begin(); it != playerlist.end(); it++){
cout << "socket numbers " << (*it)->socketno << endl;
/* (*it)->socketno gives me a bunch of random numbers,
not the socket numbers I was looking for! */
}
return true;
}
bool RoomDB::addPlayer( GamePlayer *playerpoint ) {
roomlist[1].playerlist.push_back( playerpoint );
// This adds the player object to the Gameroom object
cout << "player point " << playerpoint->socketno << " roomno: " << roomno;
// This shows everything should be ok so far
return true;
}
The most likely explanation is that you're calling addPlayer with a pointer than becomes invalid by the time you call logicPort. One possibility is that you call addPlayer with the address of an object on the stack, and the object disappears when the stack is unwound.
edit The problem is right here:
bool PlayerDB::addPlayer( int sid, GamePlayer tempplayer ) {
...
roomman.addPlayer( &tempplayer, tempplayer.roomno );
}
PlayerDB::addPlayer takes the second argument by value. This means that it gets a copy that exists for the lifetime of the method. You then take the pointer to that copy, and add it to the list. Once PlayerDB::addPlayer returns, the pointer becomes invalid.
It's hard to suggest a good fix without seeing more code. One possibility is to make PlayerDB::addPlayer take a pointer as its second argument, and make sure you don't repeat the same mistake one level up the call chain.
An even better possibility is to turn playerlist into list<GamePlayer>: from your code there doesn't appear to be any need for the list to contain pointers. This will simplify things greatly.