Apologies ahead of time, as I am not even sure how to phrase the question, but I was working on a homework assignment (to which the question is unrelated except that I ran into the problem working on the assignment) and came across certain problem (this is just an extraction and generalization, I left out destructors, etc...):
class idType {
int _id;
public:
int getID() { return _id; }
idType(int in = -1) : _id(-1) {}
};
class Foo {
static int _count;
idType* _id; //int wrapper just for examples sake
public:
Foo() { _id = new idType(_count); ++_count; }
idType* getID() { if(_id) return _id; return NULL; } //ERROR WHEN CALLED FROM BELOW
};
class Bar {
Foo* _foo;
public:
Bar(Foo* foo = NULL) : _foo(foo) {}
Foo* getFoo() { if(_foo) return _foo; return NULL; }
};
int foo::_count = 0;
int main() {
Bar BAR;
if(BAR.getFoo()->getID() && BAR.getFoo()); //RUN TIME ACCESS VIOLATION ERROR
return 0;
};
As I mentioned, this is not the code I am working with, but I believe it more clearly identifies what is happening. BAR passes the getFoo() check, so _foo isn't(?) NULL but getFoo()->getID() faults at if(_id).
Is the static variable somehow preventing any NULL instance of a pointer to that class type from existing?
The reason I asked that at first was because when I commented out the static variable lines in my original program, the program worked fine. HOWEVER, after trying this code (which more or less emulates what I am doing) removing the static variable lines makes no difference, it still faults the same.
This may be simple, but I am at a loss as to what is wrong. Thank you much for any help.
Check pointers before using them.
int main()
{
Bar BAR;
Foo *pFoo = BAR.getFoo();
if (pFoo && pFoo->getID())
{
// do something
}
return 0;
};
You are not creating a Foo instance anywhere, and not passing a Foo* to the Bar constructor, so Bar::_foo gets initialize to NULL, which is what Bar::getFoo() returns. And then your if statement crashes due to your backwards use of short-circuit logic (you are trying to access Foo::getID() before first validating that Bar::getFoo() returns a non-NULL Foo* pointer).
You have to pass pointer to Foo object to BAR
int main() {
Bar BAR(new Foo);
//Reverse the condition, check for pointer validity first
if(BAR.getFoo() && BAR.getFoo()->getID());
return 0;
};
Provide the destructor to cleanup _foo after usage
~Bar() { if(_foo) delete _foo; _foo=NULL; }
Related
Under C++ I usually ran into an error.
Suppose I have the following classes:
class ClassData
{
public:
ClassData() { a=-1; }
public:
int a;
};
class MyClass
{
public:
MyClass() { m_classData = 0; }
MyClass(ClassData* classData) { m_classData = new ClassData(*classData); m_classData->a=1; }
inline bool getClassData(ClassData* classData) {
if (m_classData) { classData = m_classData; return true; }
else return false;
}
private:
ClassData* m_classData;
};
Now in the main I run this test code:
ClassData cdata;
MyClass* m_myClass = new MyClass(&cdata);
int value = 0;
ClassData classData;
if (m_myClass->getClassData(&classData))
value = classData.a;
If the code is run, value is equal to -1 (instead of 1).
First question: why I've not been able to take a reference to ClassData in MyClass? While I'm thinking to have the ClassData object of m_myClass (like doing m_myClass->m_classData if it would be public), in reality I'm calling the member a on local ClassData object.
I was thinking that the cause was that I cannot change the local variable address, but if I change the code into this:
ClassData* classData=0;
if (m_myClass->getClassData(classData))
value = classData->a;
I get my program crashing.
Second question: what is the correct way to manage this situation? Is the issue located in the program main function or in how getClassData is defined giving room for mistakes?
Here:
bool getClassData(ClassData* classData) {
if (m_classData) { classData = m_classData; return true; }
else return false;
}
Notice that classData is a local variable. It dies when the function terminates, so the function really does nothing except report whether its m_classData is null or not.
So in the first case:
ClassData classData; // <-- classData.a is -1
if (m_myClass->getClassData(&classData))
value = classData.a; // <-- classData.a is still -1
In the second case:
ClassData* classData=0; // classData is null
if (m_myClass->getClassData(classData))
value = classData->a; // classData is still null
you dereference a null pointer, which is Undefined Behavior. You're lucky all it does is crash.
A correct (but still unsafe) way to do it is like this:
bool getClassData(ClassData* classData) {
if (m_classData!=0 && classData!=0)
{ classData->a = m_classData->a; return true; }
else return false;
}
I say "still unsafe" because this function cannot really verify that these pointers point to valid data structures. To avoid this danger you must refrain from using pointers so much, and look into references.
Using values instead of pointers simplifies things and will also remove your memory leak. See live example
#include <iostream>
class ClassData
{
public:
ClassData() { a=-1; }
public:
int a;
};
class MyClass
{
public:
MyClass() { }
explicit
MyClass(ClassData const& classData) {
m_classData = classData;
m_classData.a=1;
}
ClassData const& getClassData() const {
return m_classData;
}
private:
ClassData m_classData;
};
int main()
{
ClassData classData;
MyClass myClass( classData );
classData = myClass.getClassData();
int value = classData.a;
std::cout << value;
}
I have the following exercise:
Add code to make it run properly.
class MyInt
{
public:
private:
int* MyValue;
}
int main(int argc,char** argv)
{
MyInt x(1);
...//a bit more code where the actual value of x is going to be used.
return 0;
}
I added as a private property
int val;
and a public constructor
Myint(int x)
{
val = x;
MyValue = &val;
}
I added the int val as a way for the constructor to assign to MyVal an address of an object that is not temporary, as the x.
Is there a neat(er) way to answer this exercise?
I don't see anything in your original problem statement that requires the pointer to be initialized to the address of an int. The minimal code required to fix the example would be to add a constructor that takes an int, and initialize MyValue to nullptr.
class MyInt
{
public:
MyInt(int) {}
private:
int* MyValue = nullptr;
};
int main(int argc,char** argv)
{
MyInt x(1);
return 0;
}
If your compiler doesn't support C++11 then
class MyInt
{
public:
MyInt(int) : MyValue(NULL) {}
private:
int* MyValue;
};
Another way:
MyInt(int x) : MyValue(new int(x)) {}
This doesn't require the additional member. However, you have to make sure that you deallocate the memory in the destructor.
~MyInt() { delete MyValue; }
I'm not really sure why you want to store a pointer to an int inside a class, rather than just storing the value directly (and not have a pointer be the input to the constructor), but assuming you do actually want that, here's how you'd do it:
MyInt(int x):MyValue(new int(x)){}
But this is really, really terrible style, and you have to have a good reason for doing it. You also need to remember to free the pointer at class destruction:
~MyInt(){delete MyValue;}
I need to pass a pointer to a class so some code I don't control. This code automatically free()s the pointer when it is done, but I need the class later. I hoped I could just make a 'wrapper' class that would keep the class from being deallocated without actually preventing the code from accessing it, but virtual calls don't work.
template <class T>
class PointerWrapper:public T
{
public:
T* p;
PointerWrapper(T *ptr)
{
p=ptr;
}
~PointerWrapper(void)
{
}
T* operator->() const
{
return p;
}
T& operator*() const
{
return *p;
}
};
void codeIDontControl(Example *ex)
{
ex->virtualfunction();
delete ex;
}
void myCode()
{
Example *ex=new Example();
codeIDontControl(ex);
do something with ex //doesn't work because ex has been freed
codeIDontControl(new PointerWrapper<Example>(ex));
do something with ex //ex hasn't been freed, but the changes made to it via
// Example::virtualfunction() in codeIDontControl() aren't there anymore
}
Basically, ex->virtualfunction() calls the virtual function in PointerWrapper itself instead of the virtual function in PointerWrapper->p. It seems that it's ignoring the -> operator?
Now, I don't need to use a PointerWrapper-esque class if there's a different way to do this, but it was all I could think of...
I can't modify Example either, but I can subclass it
You should provide Forwarder class - which redirects virtual calls to stored pointer. Freeing of forwarder class will not cause releasing of pointee. This approach does NOT need to do copy (which can be expensive/may be not implemented/or even not make sense):
struct Forwarder : Example
{
Example *impl;
Forwarder(Example *i) : impl(i) {}
void virtualfunction()
{
impl->virtualfunction();
}
};
Full code:
live demo:
#include <iostream>
#include <ostream>
using namespace std;
struct Example
{
virtual void virtualfunction()=0;
virtual ~Example() {}
};
struct Implmenetation : Example
{
bool alive;
Implmenetation() : alive(true) {}
void virtualfunction()
{
cout << "Implmenetation::virtualfunction alive=" << alive << endl;
}
~Implmenetation()
{
alive=false;
cout << "Implmenetation::~Implmenetation" << endl;
}
};
struct Forwarder : Example
{
Example *impl;
Forwarder(Example *i) : impl(i) {}
void virtualfunction()
{
impl->virtualfunction();
}
};
void codeIDontControl(Example *ex)
{
ex->virtualfunction();
delete ex;
}
void myCode()
{
Implmenetation impl;
codeIDontControl(new Forwarder(&impl));
//do something with ex //doesn't work because ex has been freed
impl.virtualfunction();
}
int main()
{
myCode();
}
Output is:
Implmenetation::virtualfunction alive=1
Implmenetation::virtualfunction alive=1
Implmenetation::~Implmenetation
It's bad design, really. Only the allocator should be allowed to free memory. Functions like this are dangerous, as they leave with with dangling pointers.
This is just off the top of my head, maybe you could try something like this? It's not a safe idea, but if someone implemented it I would be interested to know what happens.
class Foo
{
Foo(Foo* copy) : m_copy(copy) {}
~Foo() { if(m_copy) { *m_copy = *this; } } // Use copy constructor to create copy on destuction.
Foo* m_copy;
}
Foo copy(NULL);
Foo* original = new Foo(©);
MethodThatDeletes(original);
// Original should be destroyed, and made a copy in the process.
original = NULL;
// Copy should be a copy of the original at it's last know state.
copy;
You are providing a Example* to codeIDontControl. The overloaded operator-> on PointerWrapper is an for the PointerWrapper type not the Example* type or even the PointerWrapper* type (i.e. for a value or reference of that type not a pointer to that type).
Since the function you need to call isn't controlled by you, you will need to provide a complete wrapper of the type it expects as a wrapper over the instance you wish to control the lifetime of.
I have to make some kind of bridge between two pieces of software, but am facing an issue I don't know how to deal with. Hopefully someone will have interesting and (preferably) working suggestions.
Here is the background : I have a C++ software suite. I have to replace some function within a given class with another function, which is ok. The problem is that the new function calls another function which has to be static, but has to deal with members of the class. This is this second function which is making me mad.
If the function is not static I get the following error :
error: argument of type ‘void (MyClass::)(…)’ does not match ‘void (*)(…)’
If I set it to static I get either the following error :
error: cannot call member function ‘void
MyClass::MyFunction(const double *)’ without object
or
error: ‘this’ is unavailable for static member functions
depending on if I use or not the "this" keyword ("Function()" or "this->Function()").
And finally, the class object requires some arguments which I cannot pass to the static function (I cannot modify the static function prototype), which prevents me to create a new instance within the static function itself.
How would you deal with such a case with minimal rewriting ?
Edit : Ok, here is a simplified sample on what I have to do, hoping it is clear and correct :
// This function is called by another class on an instance of MyClass
MyClass::BigFunction()
{
…
// Call of a function from an external piece of code,
// which prototype I cannot change
XFunction(fcn, some more args);
…
}
// This function has to be static and I cannot change its prototype,
// for it to be passed to XFunction. XFunction makes iterations on it
// changing parameters (likelihood maximization) which do not appear
// on this sample
void MyClass::fcn(some args, typeN& result)
{
// doesn't work because fcn is static
result = SomeComputation();
// doesn't work, for the same reason
result = this->SomeComputation();
// doesn't work either, because MyClass has many parameters
// which have to be set
MyClass *tmp = new MyClass();
result = tmp->SomeComputation();
}
Pointers to non-static member functions are a bit tricky to deal with. The simplest workaround would just be to add an opaque pointer argument to your function which you can then cast as a pointer to 'this', then do what you need with it.
Here's a very simple example:
void doSomething(int (*callback)(void *usrPtr), void *usrPtr)
{
// Do stuff...
int value = callback(usrPtr);
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
doSomething(myCallback, this);
}
private:
int value_;
static int myCallback(void *usrPtr)
{
MyClass *parent = static_cast<MyClass *>(usrPtr);
return parent->value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
In this example myCallback() can access the private value_ through the opaque pointer.
If you want a more C++-like approach you could look into using Boost.Function and Boost.Bind which allow you to pass non-static member functions as callbacks:
void doSomething(boost::function<int ()> callback)
{
// Do stuff...
int value = callback();
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
doSomething(boost::bind(&MyClass::myCallback, this));
}
private:
int value_;
int myCallback()
{
return value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
If you really can't change the function prototype you could use a global pointer, but that opens up all sorts of issues if you will ever have more than one instance of your class. It's just generally bad practice.
class MyClass;
static MyClass *myClass;
void doSomething(int (*callback)())
{
// Do stuff...
int value = callback();
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
myClass = this;
doSomething(myCallback);
}
private:
int value_;
static int myCallback()
{
return myClass->value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
Following spencercw's suggestion below the initial question I tried the "static member variable that you set to point to this" solution (the global variable would have been tricky and dangerous within the context of the software suite).
Actually I figured out there was already something like this implemented in the code (which I didn't write) :
static void* currentObject;
So I just used it, as
((MyClass*)currentObject)->SomeComputation();
It does work, thanks !!!
non-reentrant and non-thread-safe way is to pass "this" address using global variable.
You can move the result = SomeComputation(); out of your static function and place it in BigFunction right before your call to the static function.
Consider the following code:
struct data
{
int foo;
int bar;
};
data a;
a.foo = 200;
a.bar = 300;
static void update(data* a, int rspec)
{
if (!rspec) //my data management
{
3rdPartyApi->CreateStream();
3rdPartyApi->PushData(a->foo);
3rdPartyApi->PushData(a->bar);
3rdPartyApi->CloseStream();
}
else // internal data management
{
3rdPartyApi->CreateStream();
3rdPartyApi->PushData(3rdPartyApi->BufferQueue);
3rdPartyApi->CloseStream();
}
3rdPartyApi->PushStream(3rdPartyApi->GetLastStreamBuffer().POD());
}
Lets say I change the value of a.foo or a.bar, and it requires me to call Update there-after the assignment. Can this be done, without actually calling Update() on each change manually?
[EDIT]
Note that the update function created is also assigned to a function pointer for
the third party API, so it can do it's own internal updating. So making the update function non-global is impossible, and thus is why the current update function is global.
[EDIT]
I also rewrote my example to be more understanding and correct to the actual API I'm using
e.g
3rdPartyApi->StreamUpdate((void (*)(void*, int))update);
Yes, you can. Use class methods for this. Pass a static method from your class to the 3rd party API as an update function.
class data
{
public:
void set_foo(int new_foo);
void set_bar(int new_bar);
int get_foo() const;
int get_bar() const;
// This is the update signature which the 3rd party API can accept.
static void update(void* ptr, int rspec);
private:
// These are private so we can control their access.
int foo;
int bar;
};
void data::set_foo(int new_foo)
{
foo = new_foo;
// 'this' is a special pointer for current data object.
update(this);
}
void data::set_bar(int new_bar)
{
bar = new_bar;
update(this);
}
int data::get_foo() const
{
return foo;
}
int data::get_bar() const
{
return bar;
}
// This is needed if the 3rd party API can only call C bindings.
// If it's a C++ API this is not needed.
extern "C" {
void data::update(void* ptr, int rspec)
{
if (!rspec) //my data management
{
// You have to cast to data* from void*.
data* data_ptr = reinterpret_cast<data*>(ptr);
3rdPartyApi->CreateStream();
3rdPartyApi->PushData(data_ptr->foo);
3rdPartyApi->PushData(data_ptr->bar);
3rdPartyApi->CloseStream();
}
else // internal data management
{
3rdPartyApi->CreateStream();
3rdPartyApi->PushData(3rdPartyApi->BufferQueue);
3rdPartyApi->CloseStream();
}
3rdPartyApi->PushStream(3rdPartyApi->GetLastStreamBuffer().POD());
}
} /* extern "C" */
Then:
3rdPartyApi->StreamUpdate(&data::update);
data a;
a.set_foo(200);
a.set_bar(300);
Note that use of a struct instead of a class is equally fine here. But the convention is to use classes in C++. There is only a minor difference which you can learn later.
It is hard to write code for foo, bar, and data, so let's make it more concrete:
class point
{
public:
int x_coord() const;
int y_coord() const;
void move_to(int new_x, int new_y);
private:
void update_3rd_party();
int x;
int y;
};
void point::move_to(int new_x, int new_y)
{
x = new_x;
y = new_y;
// whatever else needs to be done
update_3rd_party();
}
You need to make use of Observer design pattern or a slight variant of it.
See this example here.
The usual way would be to turn foo and bar into some type that overloads the assignment operator:
class updated_int {
int value;
public:
updated_int(int init = 0) : value(init) {}
updated_int &operator=(int new_val) {
value = new_val;
update();
return *this;
}
// You might want to declare this private and not implement it.
updated_int &operator=(updated_int const &r) {
value = r.value;
update();
return *this;
}
operator int() { return value; }
};
struct data {
updated_int foo;
updated_int bar;
}
data a;
a.foo = 1; // operator= will call update() automatically.