C++ Detecting an implicit cast of 0 to a class - c++

I am calling a function in a API that returns a Answer object. Under some conditions, the API will return EMPTY_answer, which is defined as such:
#define EMPTY_answer ((Answer)0)
of course, attempting to access a Answer variable or function from an EMPTY_answer object crashes the application.
Trying to test for it using if(lAnswer == EMPTY_answer) also crashes the application. Is there any way to detect if the API is returning EMPTY_answer?
Edit:
I didn't code the api and I can't modify it in any way, I'm just digging through .h files trying to figure this out. And yes, I am aware that casting 0 to a class is a bit too creative to put it mildly. I just noticed that the == operator is overridden
(...)
class ExportedByJS0CORBA Answer
{
(...)
int __stdcall operator==(Answer *ipt) const;
}
the function being called is
static SubClassOfAction Query();
I'm simplifying names and quite a few layers of inheritance
To be more precise, it crashes with a Segmentation Fault.

Instead of doing a very ugly cast which is almost guaranteed to trigger undefined behavior, just make a static global variable which is used as the "empty" answer. You don't need to use this object in any way, just make it exist so it can be used as a sentinel.
In Answer.h:
extern const Answer EMPTY_answer;
In Answer.cpp:
const Answer EMPTY_answer; // use any constructor parameters that will be appropriate

If Answer is a class type, as the text of your questions suggest, then (Answer) 0 will construct a temporary Answer object using the constructor that accepts 0 as an argument (apparently such constructor exists). In this case attempting to access the members of that object will not crash anything, unless Answer class is specifically implemented to crash in this case (intentionally or unintentionally). So your "Of course..." claim makes no sense whatsoever. There's no immediate reason for such code to crash.
If you observe crashed in someAnswer == EMPTY_answer comparison, that would either mean that the implementation of == operator is buggy, or that either the LHS or the RHS are not valid objects. For example, it might turn out that it is illegal (by design) to construct an Answer object by conversion from 0. If so, then you should simply stop using (Answer) 0 in your code and find another, correctly supported object value to indicate an empty answer.

your original method of just checking for EMPTY_answer is the right way to solve this. Your real problem is why that crashes. What type is lAnswer? Or Answer for that matter... you can't cast 0 to a class like that.

Related

Smart Pointer advanced implementation [help, advice, feedback]

I'd like to get deeper in C++. There are decisions made in STL that I'd like to understand and it's quite hard from just the code.
My idea is to implement some of the STL on my own to understand the pitfalls and so improve my understanding of C++ and improve my code. And I'd like to have some features in STL containers the STD does not have like destruction notification for a resource handling class. I created an extended version of my SharedPointer to contain a std::function as deletion notifier.
And I found some trouble.
Take this code for example: SmartPointer.hpp
This is some code I came up with and have some questions.
Short:
Known problems
Derived classes won't work
Complains about incomplete type
Unknown problems
Long:
1.1. Derived classes won't work
Just having T as type won't work after the type has been casted. The idea was to pass along OrigT as second parameter so I always know what type ptr points to. I can cast it back and call the correct destructor.
Considering
SharedPointer<Derived> member = base.Cast<Derived>();
will create T = OrigT and types will not match after cast on assertion I assume. I can't imagine anything how I could solve this.
if (!shared->HasReferences())
{
delete shared;
OriginalValuePointer origPtr = dynamic_cast<OriginalValuePointer>(ptr);
delete origPtr;
}
1.2. Complains about incomplete type
In my examples I get complaints about incomplete type. But I can't figure out why. Currently I am considering making operator* and operator-> templates, too that would be a shot in the dark. I have no clue why it complains and I'd like to ask if you could point me to the problem here.
Same code as above in compiler complaint
2.2. I think stackoverflow is not the ideal place to ask for feedback but considering my two problems I'd like to ask anyway.
Does anyone have any sources to readable and ideally explained smart pointers? The ones I've found did not quite match my expectations. They were either too simple or did not contain explanation at the critical points.
I'd appreciate some direct feedback on the code. Afar from coding style of course ;-). Is there anything you directly see where I made a mistake I'll regret? Is there anything that could be done better? (for example, .Cast as member is IMHO a bad choice. For once it is not directly a property of the pointer and I think it might cause flaws I'm not aware of yet.)
I'm really grateful for your help and your opinion.
Stay healthy.
Normal C++ classes use snake_case, rather than CamelCase.
This class isn't' thread safe (you probably knew that, but its worth calling out)
NumReferences returns the count by reference, which isn't useful, and is slightly slower than returning by int.
All methods defined inside the class are automatically inline, so you don't need that anywhere.
operator ValueType() is implicit, which is super dangerous. You can make it explicit, but I'd eliminate it entirely.
operator ValueType() needs to know the details of ValueType in order to be created. So if ValueType isn't fully defined yet, you'll get compiler errors about an incomplete type. Again, deleting the method eliminates this issue.
operator SharedPointer<U>() and operator bool() are also implicit. Prefer explicit.
strongly consider adding assert to all your methods that use shared or ptr without checking if it's null first.
Raw() is normally named get()
Now, on to OrigT and Release: std::shared_ptr does an interesting trick where the SharedData has inheritance:
struct SharedData {
std::atomic_uint count;
virtual ~SharedData() {}
};
template<class OrigT>
struct SharedDataImpl {
OrigT* data;
~SharedData() {delete data;}
};
Since all the shared_ptrs to the same data will point to the same SharedDataImpl, they don't have to know the most derived class. All they have to do is delete the SharedData member, and it'll automatically clean up the data correctly. This does require having a second data pointer: one in the SharedPointer itself and one in the SharedData, but usually this isn't an issue. (Or a virtual T* get() method)

Align A Pointer To Have A Functional -> Operator? C++

This quesiton is composed of a couple parts, the first has to do with the -> operator in a class. Does it take some sort of input (according to the C++ standard)? For example
some_return_type? operator->( long address ) {
cast the address to some sort of pointer and do something with it...
return something?...possibly... maybe not?;
}
So in reality A::SomeMethod() would refer to an address for a function in memory passed to ->. Or
A::someStaticOrNonStaticDataMember would refer to an address for a field?
If so (given that we do not have access to the actual type of the class), or something like this exists, what is it, and can we reconstruct part of a pointer, or align a pointer, (or write a class with an algorithm to do this), for a class based on some information about that class, so that it had an operable -> operator, so one could write:
somePointer->A::SomeMethod();
and have it call A::SomeMethod()? And maybe make context for the memory used in the class?
From the comments it seems you want to control how Compiler handles and generates -> tokens. This is for your bad luck not possible, because Compiler doesn't expose such information, nor is it required by Standard to do so
It is like you are trying to have "dynamic" (the C# type) but in C++, unluckily this is not possible. What could be similiar is wrapping some sort of "Closure collection" addressed by strings (a sort of scripting language) but that would be really heavy and not very nice.
Actually doing what you want with the syntax you showed is not possible.
If the type of an object is not known, then you have that object hided behind a "void *". That means basically that the only way you can use that object is by casting it back to its original type.
Suppose you have a DLL that expose 2 functions (with header files)
// creates an object of given type or null_ptr if no object match
void* getObject(std::string obj_type);
// call a method on that object
void callMethod(void* obj, std::string method_name, void* args, void* returnval);
Actually that solution (even if ugly) allows to call methods on objects that you don't know (it could be a lot better than that.)
But that force you to use void* and strings. That's because how C++ resolve method names (in reality also in C# the "dynamic" type generates behind the scenes reflection code that use strings with method names and is particulary slow)
So something similiar can be achieved with
float fuelLiters = 3.0f;
void * myObj = createObject("SomeCar");
callMethod(myObj,"loadFuel", &fuelLiters, null_ptr);
you probably can make the syntax a little better with templates or some macro, but you'll never be able to do something like
myObj->A::loadFuel(fuelLiters);
What you can do is having the externally loaded class, use the same interfaces of your application, says:
class ICar{
public:
void loadFuel(float liters)=0;
};
In that case you can use a function that cast the opaque object handle to ICar. This is what I already doing in a library I wrote 2 years ago:
So you just need the DLL expose a method for casting the class (downcast)
//if given object is implementing a ICar, the correct pointer is returned, else
// this function will return nullptr (or throw exception if you like more)
void * downcast( typeof(ICar), myObj);
You'll need simply
ICar *myCar = static_cast<ICar>(downcast( typeof(ICar), myObj));
myCar->loadFuel(3.0f);
However note that both the DLL and your application should "know" about what "ICar" is, so they must include the "ICar" header.
doing that is definitely possible, I did it already in 2 different ways, so If you need more details about implementation I'll be happy to show a possible way (given I understood correctly your question).
The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members.
foo->bar() is the same as (*foo).bar()
If you want to overload -> you should also overload *

C++: use of “().” and “()[].”

I am trying to understand the programming of Siemens scanner using C++ and given that my C++ skills are limited, I am having problems in understanding many parts of the code provided by the vendor.
Problem 1
For instance, the code uses reference (rMrProt) to object MrProt and notations (such as the use of use of (). and ()[].) are very confusing to me.
For instance:
ImageSamples = rMrProt.kSpace().baseResolution()
ImageSize = rMrProt.sliceSeries()[0].readoutFOV()
Some explanation of these statements would be appreciated.
All information regarding object MrProt are in “MrProt.h”, “MrProt.dll”, “MrProt.lib”. All these files have been shared at:
https://docs.google.com/open?id=0B0Ah9soYnrlIYWZkNDU2M2EtYTNmNC00YTc5LTllMzItYzIyMWU4M2ZhY2Fi
Problem 2
Also, I have been trying to read MrProt.dll and MrProt.lib without any success. Only now, I came to know of dumpbin. Any help would be appreciated.
Problem 3
Another confusion that I have is related to some part of MrProt.h itself. There is a statement in MrProt.h:
class __IMP_EXP MrProt: public MrProtocolData::MrProtDataDelegate
{
typedef MrProtocolData::MrProtDataDelegate BasicImplementation;
public:
MrProt();
MrProt(const MrProt& rSource);
…
….
}
Here, __IMP_EXP, I guess that it’s some compiler specific stuff.. some decoration etc. But, I still have no idea what to make of this.
Problem 1.
rMrProt.sliceSeries()[0].readoutFOV()
means
Take rMrProt's sliceSeries member and call that. Apparently, it returns an array-like object, something that can be indexed.
From the result, take the first element ([0]). That's some kind of object.
On that element/object, call readoutFOV.
Problem 2. You're not really supposed to read binary files. There should be documentation with them.
1)
ImageSamples = rMrProt.kSpace().baseResolution()
This is just method chaining. You call the method kSpace() on rMrPrto which returns an object, and you call baseResolution() on that object.
2) Those are binary files. What would you expect to see? To read them you'd have to be an expert in asm or at least know some low-level concepts.
3) __IMP_EXP is a common type of directive that tells the compiler that the class is either exported or imported.
It expands to _declspec(dllimport) or _declspec(dllexport), depending on whether the definition of the class is in the current module or another module.
identifier() is a method/function call
identifier[i] returns the i'th element in an array.
identifier()[i] returns the i'th element of the array returned by identifier()
I can only help on problem 1:
if the return value of rMrProt.kSpace() is a struct. instead of saving it to a struct and then access it's member you can directly access a member of his with rMrProt.kSpace().MemberName
same for rMrProt.sliceSeries() which I guess is returning an array. so rMrProt.sliceSeries()[0] will access the first value in the returning array.

Does it make sense to use const in an interface or not?

I have a module that performs some calculations and during the calculations, communicates with other modules. Since the calculation module does not want to rely on the other modules, it exposes an interface like this (this is a very simplified version of course):
class ICalculationManager
{
public:
double getValue (size_t index) = 0;
void setValue (size_t index, double value) = 0;
void notify (const char *message) = 0;
};
Applications that want to use the calculation module need to write their own implementation of the interface, and feed it to the calculation tool, like this:
MyCalculationManager calcMgr;
CalculationTool calcTool (calcMgr);
calcTool.calculate();
I am wondering now whether it makes sense to add "const" to the methods of the ICalculationManager interface.
It would seem logical that the getValue method only gets something and doesn't change anything, so I could make this const. And setValue probably changes data so that won't be const.
But for a more general method like notify I can't be sure.
In fact, for none of the methods I can now for sure that the method is really implemented as a const method, and if I would make the interface methods const, I am forcing all implementations to be const as well, which is possibly not wanted.
It seems to me that const methods only make sense if you know beforehand what your implementation will be and whether it will be const or not. Is this true?
Doesn't it make sense to make methods of this kind of interface const? And if it makes sense, what are good rules to determine whether the method should be const or not, even if I don't know what the implementation will be?
EDIT: changed the parameter from notify from "char *" to "const char *" since this lead to irrelevant answers.
You make a function const when you are advertising to clients that calling the function will never change the externally visible state of the object. Your object only has one piece of state that can be retrieved, getValue.
So, if getValue can cause the next getValue to return a different value then sure, leave it non-const. If you want to tell clients that calling getValue() will never change the value returned by the next getValue() then make it const.
Same for notify:
double d1 = mgr->getValue(i);
mgr->notify("SNTH"); // I'm cheating.
double d2 = mgr->getValue(i);
assert(d1==d2);
If that should hold true for all cases and all i's then notify() should be const. Otherwise it should not be.
Yes. One should use const whenever and wherever it is sensible to do so. It doesn't make sense that the method for performing a calculation (which is what your interface suggests) should change it's observable behavior because it had "notify" called on it. (And for that matter, how is notification related to calculation at all?)
My making one of the interface members const, you don't force clients to be const -- you merely allow them use of a const ICalculationManager.
I would probably make Notify const. If clients need to do something non-const as a result of a notification, then Notify is not a good method name -- that name suggest non-state-modifying transformations such as logging, not modification.
For instance, most of the time you pass your interface around, you're going to want to use pass-by-reference-to-const to pass the interface implementor, but if the methods aren't const, you cannot do that.
The interface should be guiding the implementation, not the other way around. If you haven't decided if a method or parameter can be const or not, you're not done designing.
Using const is a way of making assertions about what the code is or is not allowed to do. This is extremely valuable in reasoning about a piece of code. If your parameter to notify isn't const for example, what changes would it make to the message? How would it make the message larger if it needed to?
Edit: You appear to know the value of declaring a const parameter, so lets build on that. Suppose you want a function to record the value of a calculation:
void RecordCalculation(const ICalculationManager *calculation);
The only methods you'll be able to call on that pointer are the const methods. You can be sure that after the function returns, the object will be unchanged. This is what I meant by reasoning about the code - you can be absolutely certain the object won't be changed, because the compiler will generate an error if you try.
Edit 2: If your object contains some internal state that will be modified in response to operations that are logically const, such as a cache or buffer, go ahead and use the mutable keyword on those members. That's what it was invented for.
For me it only depends on the contract of your interface.
For a getter method I do not see why it should change any data and if this happens, maybe mutable is an option.
For the setter method I agree, not const there because this will certainly change data somehow.
For the notify is hard to say without knowing what it means for your system. Also, do you expect the message parameter to be modified by the implementation? If now, it should be const too.
Without reading your entire post: Yes of course, it makes sense if you want to use an object (which inherits ICalculationManager) in a const context. Generally, you should always use const qualifier if you don't manipulate private data.
EDIT:
Like Mark Ransom said: You need to know exactly how your interface functions should behave, otherwise your not finished designing.
I know I'm going to get a lot of downvotes for this, but in my opinion the usefulness of const-correctness in C++ is vastly exaggerated. The const idea is primitive (it only captures one bit of concept... change/don't change) and comes with an high cost that even includes necessity of code duplication. Also it doesn't scale well (consider const_iterators).
What's more important I cannot remember even a single case (not even ONE) in which the const-correctness machinery helped me by spotting a true logical error, that is I was trying to do something that I shouldn't do. Instead every single time the compiler stopped me there was a problem in the const declaration part (i.e. what I was trying to do was logically legit, but a method or a parameter had a problem in the declaration about const-ness).
In all cases I can remember where I got a compiler error related to const-correctness the fix was just adding some missing const keywords or removing some that were in excess... without using the const-correctness idea those errors wouldn't have been there at all.
I like C++, but of course I don't love to death every bit of it (digression: when I interview someone a question I often ask is "what is the part you don't like about <language> ?" ... if the answer is "none" then simply means that who I'm talking to is still in the fanboy stage and clearly doesn't have a big real experience).
There are many parts of C++ that are very good, parts that are IMO horrible (stream formatting, for example) and parts that are not horrible but neither logically beautiful nor practically useful. Const-correctness idea is IMO in this gray area (and this is not a newbie impression... I came to this conclusion after many many lines and years of coding in C++).
May be it's me, but apparently const correctness solves a problem that my brain doesn't have ... I've many others problems, but not the one of confusing when I should change an instance state and when I shouldn't.
Unfortunately (differently from stream formatting) you cannot just ignore the const-correctness machinery in C++ because it's part of the core language, so even if I don't like it I'm forced to comply with it anyway.
You may now say... ok, but what's the answer to the question ? It's simply that I wouldn't get too crazy about that part of the semantic description... it's just a single bit and comes with an high price; if you're unsure and you can get away without declaring constness then don't do it. Constness of references or methods is never an help for the compiler (remember that it can be legally casted away) and it has been added to C++ just as an help for programmers. My experience tells me however that (given the high cost and the low return) it's not a real help at all.

Change the address of a member function in C++

in C++, I can easily create a function pointer by taking the address of a member function. However, is it possible to change the address of that local function?
I.e. say I have funcA() and funcB() in the same class, defined differently. I'm looking to change the address of funcA() to that of funcB(), such that at run time calling funcA() actually results in a call to funcB(). I know this is ugly, but I need to do this, thanks!
EDIT----------
Background on what I'm trying to do:
I'm hoping to implement unit tests for an existing code base, some of the methods in the base class which all of my modules are inheriting from are non-virtual. I'm not allowed to edit any production code. I can fiddle with the build process and substitute in a base class with the relevant methods set to virtual but I thought I'd rather use a hack like this (which I thought was possible).
Also, I'm interested in the topic out of technical curiosity, as through the process of trying to hack around this problem I'm learning quite a bit about how things such as code generation & function look-up work under the hood, which I haven't had a chance to learn in school having just finished 2nd year of university. I'm not sure as to I'll ever be taught such things in school as I'm in a computer engineering program rather than CS.
Back on topic
The the method funcA() and funcB() do indeed have the same signature, so the problem is that I can only get the address of a function using the & operator? Would I be correct in saying that I can't change the address of the function, or swap out the contents at that address without corrupting portions of memory? Would DLL injection be a good approach for a situation like this if the functions are exported to a dll?
No. Functions are compiled into the executable, and their address is fixed throughout the life-time of the program.
The closest thing is virtual functions. Give us an example of what you're trying to accomplish, I promise there's a better way.
It cannot be done the way you describe it. The only way to change the target for a statically bound call is by modifying the actual executable code of your program. C++ language has no features that could accomplish that.
If you want function calls to be resolved at run-time you have to either use explicitly indirect calls (call through function pointers), or use language features that are based on run-time call resolution (like virtual functions), or you can use plain branching with good-old if or switch. Which is more appropriate in your case depends on your specific problem.
Technically it might be possible for virtual functions by modifying the vtable of the type, but you most certainly cannot do it without violating the standard (causing Undefined Behavior) and it would require knowledge of how your specific compiler handles vtables.
For other functions it is not possible because the addresses of the functions are directly written to program code, which is generally on a read-only memory area.
I am fairly sure this is impossible in pure C++. C++ is not a dynamic language.
What you want is a pointer to a function, you can point it to FuncA or FuncB assuming that they have the same signature.
You cannot do what you want to do directly. However, you can achieve a similar result with some slightly different criteria, using something you are already familiar with -- function pointers. Consider:
// This type could be whatever you need, including a member function pointer type.
typedef void (*FunctionPointer)();
struct T {
FunctionPointer Function;
};
Now you can set the Function member on any given T instance, and call it. This is about as close as you can reasonably get, and I presume that since you are already aware of function pointers you're already aware of this solution.
Why don't you edit your question with a more complete description of the problem you're trying to solve? As it stands it really sounds like you're trying to do something horrible.
Its simple!
For
at run time calling funcA() actually results in a call to funcB().
write funcA() similar to following:
int funcA( int a, int b) {
return funcB( a, b );
}
:-)