If I create a class in c++, it is possible to call a function of an object of this class, even if this class does not exists.
For example:
Class:
class ExampleClass
{
private:
double m_data;
public:
void readSomeData(double param)
{
m_data = param;
}
}
Any function where this class is used:
int main()
{
ExampleClass* myClass;
myClass->readSomeData(2.5);
}
Ofcourse this wouldn't function, because myClass is not defined.
To avoid such situations, I check if ExampleClass objects are a null_ptr
example:
void readSomeData(double param)
{
if(this == null_ptr)
return;
m_data = param;
}
But gcc says:
'this' pointer cannot be null in well-defined C++ code; comparison may
be assumed to always avaluate to false.
Ofcourse that is only a warning, but I think it is not nice to have this warning. Is there a better way to check if the pointer of a class is defined?
Testing it in the class is the wrong way, the warning is correct about that if your code is well defined then this must not be null, so the test should happen at the time when you call the member function:
int main()
{
ExampleClass* myClass = nullptr; // always initialize a raw pointer to ensure
// that it does not point to a random address
// ....
if (myClass != nullptr) {
myClass->readSomeData(2.5);
}
return 0;
}
If a pointer must not be null at a certain part of your code then you should do it according to CppCoreGuideline: I.12: Declare a pointer that must not be null as not_null
Micorosoft provides an Guidelines Support Library that has an implementation for not_null.
Or if possible then don't use pointers at all but std::optional.
So a code setup could look like this:
#include <gsl/gsl>
struct ExampleClass {
void readSomeData(double ){}
};
// now it is clear that myClass must not and can not be null within work_with_class
// it still could hold an invalid pointe, but thats another problem
void work_with_class(gsl::not_null<ExampleClass*> myClass) {
myClass->readSomeData(2.5);
}
int main()
{
ExampleClass* myClass = nullptr; // always initialize a raw pointer to ensure
// that it does not point to a random address
// ....
work_with_class(myClass);
return 0;
}
The best way is not use pointers at all:
int main()
{
ExampleClass myClass;
myClass.readSomeData(2.5);
}
That way there's no need for any check, and in fact, checking this inside the function is moot.
If you need nullability, use std::optional instead.
Either don't use pointers as Bartek Banachewicz has pointed out, or properly initialize and check the pointer:
int main()
{
ExampleClass* myClass= 0;
if (myClass)
myClass->readSomeData(2.5);
return 0;
}
Of course you still have to add the instantiation of the object at some point, otherwise the code is nonsense.
I am trying to access the type of a userdata so that I can process it accordingly. Imagine I have a class named as Foo:
class Foo:public CObject
{
public:
Foo():CObject(){}
int type() {return 1;}
}
class CObject
{
public:
virtual int type(void)=0;
}
The rationale is that every class extending the CObject has a type that must be made known by an integer number (later on an enum). The class Foo is bind to lua using luaWwrapper (//https://bitbucket.org/alexames/luawrapper/src/fd9c4fdbf4b25034e3b8475a2c8da66b7caab427?at=default).
Foo* Foo_new(lua_State* L)
{
Foo* f=new Foo();
lua_newuserdata(L,sizeof(f));
std::cout<<"f="<<f;
return f;
}
In Lua user calls this as:
f=Foo.new()
print(f)
Now I have a C++ function, say print:
int lua_print(lua_State* L)
{
void *ud = luaL_checkudata(L, 1, "Foo"); //ud is not zero
std::cout<<"ud="<<ud;
CObject* obj=(CObject*)ud; //Casting to CObject
int objtype=obj->type(); //program CRASHES here
}
I have seen that the program crashes cause the memory addresses of Foo and ud are not the same. I assume ud refers to the memory of stack which contains the memory adress of Foo. How can I access stack's memory address or the preferred memory address of Foo?
You have to use placement new to initialize the object in the memory returned by lua_newuserdata.
Something in the lines of
void *ud = lua_newuserdata(L,sizeof(Foo));
new (ud) Foo();
Foo_new should just return the pointer to the object.
In other words, your Foo_new would look like this:
Foo* Foo_new(lua_State* L)
{
return new Foo();
}
However, if you have no special initialization you need to do, you don't even need to write this function. This function is supplied for you by magical templates if you don't write one yourself.
When you want to get your Foo object from the Lua state, you do this:
int lua_print(lua_State* L)
{
Foo *ud = luaW_to<Foo>(L, 1); //ud is not zero
std::cout<<"ud="<<ud;
CObject* obj=(CObject*)ud;
int objtype=obj->type();
}
If CObject is registered with LuaWrapper too, you don't even need to do the manual cast. You can just do luaW_to<CObject>(L, 1);
I had some code that looked something like the following:
struct fooclass {
char data[32];
}
fooclass makefoo() {
fooclass res;
// for example:
memset(res.data, 0, sizeof(res.data));
res.data[0] = 43;
return res;
}
struct do_stuff {
const fooclass& obj;
do_stuff(const fooclass& obj_in) : obj(obj_in) { }
void operate() { /* do things with obj; */ }
}
bool put_it_to_work(struct do_stuff& f) {
f.operate();
f.operate();
return true;
}
bool call_it_all() {
do_stuff local(makefoo());
return put_it_to_work(local);
}
With gcc, the code worked fine. With MSVC2012, local.obj became corrupted.
The question is: how long does the fooclass returned by makefoo last? Should it be until the end of call_it_all, or is it just until the end of the do_stuff local(makefoo()) line and I just got lucky? I'd appreciate a reference to the standard.
Here's your problem:
struct do_stuff {
const fooclass& obj;
obj is a reference, not a proper object, so no copy is ever made of the result of makefoo(). The real object that obj references is destructed when the local object has finished being constructed, specifically when the anonymous temporary variable that makefoo() returns is destroyed.
I think you were just lucky that it worked under gcc. Perhaps the object that obj refered to was being destroyed as it should be, only its data was left in RAM and the program appeared to work properly. Perhaps MSVC was "erased" the RAM that obj referred to such that attempts to use it would fail quickly.
[Global Scope]
myClass *objA, *objB, *obj;
int objnum;
I want to switch between objA and objB and assign them alternatively to obj, so in main() I have:
int main()
{
objA = new myClass(parameters...);
objB = new myClass(parameters...);
// start with objA;
objnum = 0;
obj = objA;
}
At some point a function is called that switches between the two objects:
void switchObjects()
{
if (++objnum > 1) objnum = 0;
obj = objnum == 0 ? objA : objB;
}
And in the function where I use the object, I have:
void doYourJob()
{
int res = obj->work();
}
Now the weird thing is that if I don't assign obj to either objA or objB, it still works. I would expect an exception, instead. Even if I do obj = NULL;, it still works! What's this voodoo?
OK, I could provide a different example that brings to the same result, without using a NULL pointer:
myClass *obj[2];
int objnum;
void switchObject()
{
if (++objnum > 1) objnum = 0;
}
void doYourJob()
{
res = obj[objnum]->work();
}
int main()
{
obj[0] = new myClass(parameters...);
obj[1] = new myClass(parameters...);
objnum = 0;
}
With the above code, regardless of the value of objnum, I still get both objects working together, even if I'm calling work() on only one instance.
And if I replace the function doYourJob() with this:
void doYourJob()
{
int res1 = obj[0]->work();
int res2 = obj[1]->work();
}
I always get the results doubled, as if I were calling the function work() twice on every object.
Consider a simpler example:
#include <iostream>
struct X
{
void foo() { std::cout << "Works" << std::endl; }
};
int main() {
X* x = nullptr;
x->foo();
}
With most compilers and on most platforms, this code will appear to work fine, despite having called foo on a null pointer. However, the behaviour is technically undefined. That is, the C++ language gives no restrictions about what might happen if you do this.
Why does it work? Well, calling a member function only requires knowing the type of the object it is being called on. We know that x points at an X, so we know what function to call: X::foo. In many cases, it may be difficult or even impossible to know if a pointer points at a real object, so the compiler just lets it happen. The body of the function, in this case, doesn't actually depend on the X object actually existing, so it just works. This isn't something you can depend on though.
I am wondering how I can define an object in C whose reference will be null?
// definition of foo
...
void * bar = &foo; // bar must be null
There is some ways I could find to do it, but none fit my needs.
__attribute__((weak)) extern int foo; //not working with cygwin/gcc 3.4
__attribute__((at(0))) int foo; //only with rvds
#define foo (*(int*) 0) //cannot be embedded in a macro
Actually, I would prefer a standard compliant solution (c99), but anything working
will be ok.
Edited: The reason to do this is that bar will not always be null. Here is a more relevant example:
// macro that will define foo to a real object or to *null
DECL(foo);
int * bar = &foo;
if(bar) {
// we can call func
func(bar);
} else {
// bar undefined
exit(-1);
}
Of course this is still not very relevant, because I can use #if in my condition. The project involves in fact big structures, a lot of files, a few compilers, some cpu targets, and many programmers who generate bugs with a probability exponential to the complexity of the syntax they use. It is why I would like a simple macro to declare my foo object.
I've got to be missing something, but what doesn't work about void * bar = NULL?
In your class, you can override the & operator:
class MyClass
{
public:
MyClass() :
m_isNull(true)
{
}
MyClass(int value) :
m_isNull(),
m_value(value)
{
}
int value() const
{
/* If null, throw exception, maybe? */
return m_value;
}
bool isNull() const
{
return m_isNull;
}
/////////////////////////
// Here's the "magic". //
/////////////////////////
MyClass *operator&()
{
if(m_isNull)
return 0;
return this;
}
private:
bool m_isNull;
int m_value;
};
This produces behavior a user of MyClass would probably not expect. I'm not sure where this "feature" would be required or even wanted.
If you want to take the real address of a MyClass instance, you can use boost (as suggested in the comments to this answer):
MyClass foo;
MyClass *fooptr = &foo; // fooptr == NULL
fooptr = boost::addressof(foo); // fooptr = &foo (the real address)
Or you can use casting, so MyClass::operator&() isn't called:
struct DummyStruct {};
MyClass foo;
MyClass *fooptr = &foo; // fooptr == NULL
fooptr = &reinterpret_cast<DummyStruct>(foo); // fooptr = &foo (the real address)
What you want is a reference that holds a null address. This is extremely bad practice, but here goes:
#ifdef NON_NULL
Foo realFoo;
Foo &foo = realFoo;
#else
Foo &foo = *(Foo*)NULL;
#endif
Please, don't do it this way. auto_ptr may be a better option.
You are trying to create a symbol with an address of zero. Your last example is probably the only way of doing this within the C compiler / language.
The approach that is most likely to solve your problem is to look at the input file to the linker program. Most linkers allow you to define the label foo as zero.
In a unix ld script this is just:
foo = 0 ;
Okay, it's got to be the question, but you want to have a pointer with a value of 0?
how about
void * bar = (void*) 0;
You don't have to do all that messing about: a pointer is just a number with which the compiler associates a type; if you want the number to be 0, assign 0.
Oh, and answering another question, it's not that the language has anything to do with it, it's just you don't necessarily know what is in location 0. We had a lot of trouble with BSD code back in the day because on early BSD unices, *0 == 0 was reliably true. So people would write things like
while(*c) doSomething();
because when they dereferenced the 0x00 at the end of a string, it looked at LOCATION 0 which had the VALUE 0. Unfortunately, that wasn't necessarily true on other platforms.
I really doubt there is a way to do this in standard C99. In standard C++, you'd be hard put to reference the object once created, if you could create it, as dereferencing a null pointer constant is undefined, and a constant integral 0 in pointer constant is a null pointer constant. (Yes, you could try int i; i = 0; foo * p = reinterpret_cast<foo *>i; p->doSomething(); but the standard doesn't specify what reinterpret_cast<> does, other than in a vague and implementation-dependent way.)
So, my next question is what you're trying to accomplish here. If you're trying to twist the language in odd and interesting ways, it doesn't twist that way according to the Standard. If you've got a legitimate use for this, what would it be?
I think you're close, just a step of pointer indirection away.
Judging by your code sample, there's no need to take the address of foo.
You can accomplish what you want by creating a function that allocates and instantiates bar.
So instead of:
DECL(foo);
int * bar = &foo;
you could have:
#define FOO_IS_NULL 0
int * getFoo()
{
if( FOO_IS_NULL )
{
return 0;
}
int *tmp = malloc(sizeof(int));
*tmp = 1234;
return tmp;
}
int * bar = getFoo();
Note that this gets rid of the variable foo entirely.
The only caveat is that you now need to free(bar).
Well, here is what we have:
C++ allows overloading operator& and has templates to do the work for you, but doesn't allow dereferencing the null pointer.
C allows dereferencing the null pointer, as long as the address is taken afterwards. It also allows assigning void* to any pointer to an object.
Well, that's ideal. First, the C part, which is very easy. I don't understand your point that you cannot embed it into macros. It works fine for me.
#define foo_ (*(void*) 0)
Now, the C++ part. Put the stuff in nullp.hpp:
struct nullp {
struct proxy {
template<typename T> operator T*() {
return 0;
}
};
proxy operator&() {
return omg();
}
} foo;
Now, all we need to do is to glue things together:
#ifdef __cplusplus
#include "nullp.hpp"
#else
#define foo (*(void*) 0)
#endif
Now, you can use &foo and assign it to some pointer to some object-type.
Look, I'm sorry, but you're making this both too hard and too complicated.
If you want to call the thing in C, you need a pointer to function. So, for example, you have
/* ptr to 0-ary function returning int */
int (*func)() = NULL ; /* That's all you need. */
// elsewhere ....
int myfunc() { /* do a good thing */ }
func = myfunc ; /* function name *is* its address */
Now, in later code you can do
if(!func)
(*func)();
else
/* function not defined */
You don't need to mess with the loader, and you don't need --- and shouldn't use --- any zippy macros unless you really really have a strong reason for doing so. This is all standard C.
I don't think there's a standard way to define something that has the address 0. Or rather, it's undefined since it would then be possible to dereference 0, which is undefined (or is it platform specific?) in the standard.
What are you trying to do?
If you're using C++, you can use references:
int *foo = 0;
int &bar = *foo;
int *foo_addr = &bar; // gives NULL