Guidance Needed: Vectors of unique_ptr to dervied classes from an abstract base class - c++

I'm trying to streamline my code and make it work better and easier:
This means diving into vectors and unique_ptr, about which I've read so many good things. However, they are entirely new to me. I have read a few pages on both, but its a lot to wrap my head around.
What I'm currently doing is creating objects of abstract class the traditional way:
VirtualBaseClass* foo1= new DerviedClass1;
VirtualBaseClass* foo2= new DerviedClass2;
VirtualBaseClass* foo3= new DerviedClass3;
But since I have 3 - and quite possibly will have lots more - I want to make it easier to switch between them because I'm going to be comparing any combination of the objects each program run.
Currently, to switch, I just rename the DerviedClass for which I want to instantiate an object so I don't have to go in renaming each foo1 with foo3, etc..
VirtualBaseClass* Generic1 = new DerviedClass3;
VirtualBaseClass* Generic2 = new DerviedClass1;
But ultimately I want the user to tell the program which two objects to compare. So a good starting point seems to make this an array of the VirtualBaseClass, but from research it seems like its pain to have to delete the arrays so people recommend using smart pointers and vectors.
So I tried to use both. For unique pointers I do
unique_ptr<vBaseClass*> foo1(DerviedClass1);
unique_ptr<vBaseClass*> foo2(DerviedClass2);
unique_ptr<vBaseClass*> geneic1 = move(foo1);
However, from what I read I should be doing
unique_ptr<vBaseClass*> foo1(new DerviedClass1);
but new gives error of type specfier but since it works without it I think nothing of it.
With move(foo1) I get an error no move for instance of overload function match and on compile a whole host of other errors such as
unique_ptr<vBaseClass*> champ1 = move(foo1);
error C3867: 'Controller::foo1': function call missing argument list; use '&Controller::foo1' to create a pointer to member
error C2780: '_OutTy *std::move(_InIt,_InIt,_OutTy (&)[_OutSize])' : expects 3 arguments - 1 provided
All this is being done in my Controller.h file btw.
I'm in desperate need of guidances. I don't know if what I'm doing is even neccsary, do I need to use vectors with this? How would I even begin too? Is there a better way of doing this? How do I even get the user to tell the program which object to use? With arrays it would be enter 0 for foo1 or enter 1 for foo2 but with vectors? Is there a better way?
My acutal code
#pragma once
#include "stdafx.h"
#include "Skarner.h"
#include "MasterYi.h"
#include "Riven.h"
using namespace std;
class Controller
{
public:
Controller();
~Controller();
double PCFreq;
__int64 CounterStart;
int CounterCheck;
ofstream out;
Champion* skarner = new Skarner;//old way of doing it
//Champion* yi = new MasterYi;//old way of doing it
//Champion* riven = new Riven;//old way of doing it
//Champion** champions = new Champion*[200];
//Champion[0] = new Skarner();
//unique_ptr<Champion> skarner(Skarner);
unique_ptr<Champion> yi(new MasterYi);// doesn't work new error
unique_ptr<Champion*> riven(Riven); //works with or without *
unique_ptr<Champion*> champ1 = move(riven)//error with move
vector<unique_ptr<Champion>> pChampions;//vector of pointers to champion
//unique_ptr<Champion> champ2;
//Champion *champ1 = dynamic_cast<Champion*>(yi);
//Champion *champ2 = dynamic_cast<Champion*>(skarner);//not sure what the signficance of this is
//Leaving some methods out
};
Wow so apparently you can't use the "new" in a header file only in the cpp file. However I'm still not sure how to make good use of it now that I have it declared in the controller.cpp? I really wanted it as a member variable/instance variable.
Trying to do this. in controller.h
shared_ptr<Champion> yi;
shared_ptr<Champion> riven;
shared_ptr<Champion> skarner;
shared_ptr<Champion> champ1;
shared_ptr<Champion> champ2;
and in the .cpp to define them
Controller::Controller()
{
PCFreq = 0.0;
CounterStart = 0;
out.open("finalStats.txt");
CounterCheck = 0;
yi = shared_ptr<Champion> (new MasterYi);
riven = shared_ptr<Champion>(new Riven);
skarner = shared_ptr<Champion>(new Skarner);
champ1 = move(yi);
champ2 = move(riven);
}
The above code now seems to work but I'm failing to see any direct benefits.

Explanation
You got a * to much:
unique_ptr<vBaseClass> foo1(new DerivedClass1);
should do the trick by allocating a new DerivedClass1 with dynamic storage duration and storing the pointer to it in foo1.
As a reminder, just read the type aloud: foo1has type "unique pointer to vBaseClass".
For the crowd in the comments
The following shows the difference in usage between a raw pointer and a unique pointer:
{
int* a = new int(42);
unique_ptr<int> b(new int(42));
std::cout << *a << ", " << *b << "\n";
delete a;
}
There is no further difference. Any further problem you have is related to a different problem that is hard to pinpoint without further information.
Also, unique_ptr<Champion*> riven(Riven); is a function declaration for a function by the name of riven returning a unique_ptr<Champion*> and taking a single argument of type Riven. The reason this does not error is because it does not do what you think it does at all.
Finally, there is absolutely nothing that makes headers anything special. In fact, C++ performs text substitution before parsing, so that the actual parser does not even know anything about where the code came from anymore!
Karmic Demonstration
Code:
struct champ { virtual std::string whoami() = 0; };
struct karma : champ { std::string whoami() override { return "karma"; } };
int main() {
champ* a = new karma;
std::unique_ptr<champ> b(new karma);
std::cout << a->whoami() << ", " << b->whoami() << "\n";
}
Result:
karma, karma
Proof

unique_ptr<Champion> yi(new MasterYi);// doesn't work new error looks like a function declaration to the compiler, and new isn't valid in that context.
unique_ptr<Champion*> riven(Riven); //works with or without * also looks like a function declaration and is valid with or without the *.
unique_ptr<Champion*> champ1 = move(riven)//error with move You can't move a function into a unique_ptr.
I'm having a really hard time understanding your question but maybe you mean something like this:
unique_ptr<Champion> yi = new MasterYi;
unique_ptr<Champion> riven = new Riven;
std::vector<std::unique_ptr<Champion> > pChampions = { new Skarner };

Related

Any way to grab struct from DLL using dlsym (Dynamic Linking) without header file (.h)?

I have been looking everywhere for this question, but I cannot seem to get the answer for this.
So, every example I have been to is simply how to grab function pointers from SO file, which I have done. However, let just say I have this compiled as my .SO file:
(these codes compiled into libsampleso.so):
sampleso.hpp:
#IFNDEF SAMPLESO_HPP__
#DEFINE SAMPLESO_HPP__
struct carDescriptor
{
const char* model;
int prod_year;
int wheel_num;
const char* license_plate;
const char* colour;
} car;
carDescriptor fillCarID(void);
#ENDIF
sampleso.cpp:
#include "sampleso.hpp"
//Struct car fillup function
carDescriptor fillCarID(void)
{
car.model = "Ford Fiesta";
car.prod_year = 2014;
car.wheel_num = 4;
car.colour = "Midnight Blue";
car.license_plate = "D 1234 ABC";
return car;
}
now, compiled, I've got these out of objdump -T libsampleso.so: car (the struct) and _Z9fillCarIDv (the function).
if the return value of _Z9fillCarIDv() (aka fillCarID()) is normal datatype (e.g. string or int), it's easy with dlsym. However, for this I need to cast the struct first and then the function. I've tried creating an empty struct, and then cast dlsym to it:
struct carDesc * cars;
cars = reinterpret_cast<struct carDesc*>(dlsym(hHandler,"car"));
but seems to be impossible to use that as the datatype for the function:
carDesc(*__fn_fillCarIDv)(void);
__fn_fillCarIDv = reinterpret_cast<carDesc(*)(void)>(dlsym(hHandler,"_Z9fillCarIDv"));
cars = __fn_fillCarIDv(); //doesn't work, error: function returns incomplete type "carDesc" C/C++(862)
Anyone ever tried to grab a struct using dlsym without .h file?
Also, how do you deal with the elements from the struct grabbed by dlsym? I know that you don't have the proper elements listed without .h file, and obviously some pointer shifting is necessary, but can anyone give me an example of how to do it?
Thanks

Convert data type a of class object (C++)

I am writing a game in which one Object has an ability to turn into an object of another class (e.g. Clark Kent -> Superman). I would like to know what is the most efficient way to implement this.
The logic of my current code:
I have created a turnInto() function inside the ClarkKent class. The turnInto function calls the constructor of Superman class, passing all needed infos to it. The next step is to assign the address of Superman object to the current ClarkKent object.
void ClarkKent::turnInto() {
Superman sMan(getName(), getMaxHP(), getDamage());
&(*this) = &w; // <- error here
this->ClarkKent::~ClarkKent();
}
As you might have guessed, the compiler gives an error that the expression is not assignable. Not sure how to find a correct solution to this.
Keep it simple and don't play tricks you don't understand with your objects.
Superman ClartkKent::turnInto() {
return {getName(), getMaxHP(), getDamage()};
}
At the callee:
ClartkKent some_guy{...};
auto some_other_guy = some_guy.tunInto();
Or if you need something fancy:
using NotBatman = std::variant<ClartkKent, Superman>;
NotBatman some_guy = ClartkKent{...};
using std::swap;
swap(some_guy, some_guy.tunInto());
IDK

dereferencing this causes Segmentation fault

I have the following functions
LinearScheme::LinearScheme() {
cout << " empty constructor" << endl;
}
void LinearScheme::init(
int tableId,
std::string &basePath,
std::vector<size_t> &colElemSizes,
TupleDescMap &tupleDescMap,
size_t defaultMaxFragmentSize,
int numCols,
BoundBases &bounds,
std::vector<int> &colsPartitioned )
{
// This linear scheme ignores bounds
// it could be improved to use colsPartitioned for ordering (TODO)
cout << "init Linear Scheme " << endl;
*this = LinearScheme(); //SEGFAULTS HERE
cout << "after cons here?" << endl;
// init private fields
this->tableId_ = tableId;
this->basePath_ = basePath;
this->colElemSizes_ = colElemSizes;
this->numCols_ = numCols;
this->tupleDescMap_ = tupleDescMap;
this->numFragments_ = 0;
this->defaultMaxFragmentSize_ = defaultMaxFragmentSize;
// fragmentSizesFilename_ init
fragmentSizesFilename_ = basePath_ + boost::lexical_cast <string>(tableId_)
+ "_cs";
struct stat st;
// open existing file if exists. Create new otherwise.
if (stat(fragmentSizesFilename_.c_str(), &st) == 0) // file existed
openExisting();
else
createNew();
}
The reason I am initializing in init rather than constructor is because LinearScheme extends a PartitionScheme (super class with virtual methods) class and another class does that where the constructor is used recursively.
I have a QuadTree class which does the same initialization because each QuadTree constructor is applied recursively. *this = QuadTree(bounds, maxSize) line in the init function of QuadTree class works just fine.
however, this line in the other subclass (LinearScheme) *this = LinearScheme() cause a Seg fault.
Any ideas why this might happen?
EDIT
Also replacing the line:
*this = LinearScheme()
with this:
*this;
or removing it overall gets rid of the Seg Fault ... why?
Sounds like incorrect factory method / builder / deferred construction usage. For many of these object creation patterns function that constructs your objects should be a static method because there doesn't yet exist an instance to manipulate. In others you potentially manipulate an already constructed instance. In either case if you are actually constructing the object of the class type within the function you should be using new and eventually returning it.
If you are instead going for a helper method to assist with initialization then you simply shouldn't be constructing the object within the method itself, and you should just be initializing parts of it within your helper.
A factory pattern example:
LinearScheme* LinearScheme::create(...all_your_args....) {
/* construct the thing we are building only if it
* pass any arguments into him that he can handle directly if you'd like
*/
LinearScheme *out = new LinearScheme(...);
/* do whatever else you have to do */
....
return out;
}
or this helper of sorts that you seem to want
/* this time let's just do 'init' on your object */
void LinearScheme::init(....args....) {
/* possibly check if init has been done already */
if ( this->init ) return;
/* proceed to do your initialization stuff
* but don't construct the 'this' instance since it should already exist
*/
this->init = true; //so we don't init again if you don't need multiple init's
}
Alternatively you can consider the delegate constructor methods in C++11 alex mentions.
However neither of these really strikes me as being the actual problem here.
It's not working because either you probably don't even have a valid *this to deference. This could be because of your usage, or it could be because one failed to create potentially because of infinite recursion.
Here's a wikipedia link on the pattern: http://en.wikipedia.org/wiki/Factory_method_pattern
Given what you have said about having to keep passing a dozen arguments around both to parent classes and for your recursive construction, one suggestion you could consider is making a small config struct that you pass along by reference instead of all the discrete parameters. That way you don't have to keep adjusting every signature along the way each time you add / remove another parameter.
The other idea is to seperate entirely the construction of one of your objects from the responsibility of knowing how, where, and when they should be contructed and inserted into your hierarchy. Hard to say without understanding how you will actually be using LinearSchme and what the interface is.
"...in the other subclass (LinearScheme) *this = LinearScheme()"
"The LinearScheme constructor is empty: LinearScheme::LinearScheme()"
if *this is a subclass of LinearMethod, LinearMethod's constructor should already have been called and this line is useless. Besides it calls assignment operator - is it properly defined?
It is better to rely on built-in mechanism of constructing of objects. If you want to avoid code repetition, use C++11 delegating constructors feature. It was specially designed to eliminate "init" methods.
Although, "If there is an infinitely recursive cycle (e.g., constructor C1 delegates to another constructor C2, and C2 also delegates to C1), the behavior is undefined."
So it is up to you to avoid infinite recursion. In your QuadTree you can consider creating nullptr pointers to QuadTreeNode in constructor.

luabind: cannot retrieve values from table indexed by non-built-in classes‏

I'm using luabind 0.9.1 from Ryan Pavlik's master distribution with Lua 5.1, cygwin on Win XP SP3 + latest patches x86, boost 1.48, gcc 4.3.4. Lua and boost are cygwin pre-compiled versions.
I've successfully built luabind in both static and shared versions.
Both versions pass all the tests EXCEPT for the test_object_identity.cpp test which fails in both versions.
I've tracked down the problem to the following issue:
If an entry in a table is created for NON built-in class (i.e., not int, string, etc), the value CANNOT be retrieved.
Here's a code piece that demonstrates this:
#include "test.hpp"
#include <luabind/luabind.hpp>
#include <luabind/detail/debug.hpp>
using namespace luabind;
struct test_param
{
int obj;
};
void test_main(lua_State* L)
{
using namespace luabind;
module(L)
[
class_<test_param>("test_param")
.def_readwrite("obj", &test_param::obj)
];
test_param temp_object;
object tabc = newtable(L);
tabc[1] = 10;
tabc[temp_object] = 30;
TEST_CHECK( tabc[1] == 10 ); // passes
TEST_CHECK( tabc[temp_object] == 30 ); // FAILS!!!
}
tabc[1] is indeed 10 while tabc[temp_object] is NOT 30! (actually, it seems to be nil)
However, if I use iterate to go over tabc entries, there're the two entries with the CORRECT key/value pairs.
Any ideas?
BTW, overloading the == operator like this:
#include <luabind/operator.hpp>
struct test_param
{
int obj;
bool operator==(test_param const& rhs) const
{
return obj == rhs.obj;
}
};
and
module(L)
[
class_<test_param>("test_param")
.def_readwrite("obj", &test_param::obj)
.def(const_self == const_self)
];
Doesn't change the result.
I also tried switching to settable() and gettable() from the [] operator. The result is the same. I can see with the debugger that default conversion of the key is invoked, so I guess the error arises from somewhere therein, but it's beyond me to figure out what exactly the problem is.
As the following simple test case show, there're definitely a bug in Luabind's conversion for complex types:
struct test_param : wrap_base
{
int obj;
bool operator==(test_param const& rhs) const
{ return obj == rhs.obj ; }
};
void test_main(lua_State* L)
{
using namespace luabind;
module(L)
[
class_<test_param>("test_param")
.def(constructor<>())
.def_readwrite("obj", &test_param::obj)
.def(const_self == const_self)
];
object tabc, zzk, zzv;
test_param tp, tp1;
tp.obj = 123456;
// create new table
tabc = newtable(L);
// set tabc[tp] = 5;
// o k v
settable( tabc, tp, 5);
// get access to entry through iterator() API
iterator zzi(tabc);
// get the key object
zzk = zzi.key();
// read back the value through gettable() API
// o k
zzv = gettable(tabc, zzk);
// check the entry has the same value
// irrespective of access method
TEST_CHECK ( *zzi == 5 &&
object_cast<int>(zzv) == 5 );
// convert key to its REAL type (test_param)
tp1 = object_cast<test_param>(zzk);
// check two keys are the same
TEST_CHECK( tp == tp1 );
// read the value back from table using REAL key type
zzv = gettable(tabc, tp1);
// check the value
TEST_CHECK( object_cast<int>(zzv) == 5 );
// the previous call FAILS with
// Terminated with exception: "unable to make cast"
// this is because gettable() doesn't return
// a TRUE value, but nil instead
}
Hopefully, someone smarter than me can figure this out,
Thx
I've traced the problem to the fact that Luabind creates a NEW DISTINCT object EVERY time you use a complex value as key (but it does NOT if you use a primitive one or an object).
Here's a small test case that demonstrates this:
struct test_param : wrap_base
{
int obj;
bool operator==(test_param const& rhs) const
{ return obj == rhs.obj ; }
};
void test_main(lua_State* L)
{
using namespace luabind;
module(L)
[
class_<test_param>("test_param")
.def(constructor<>())
.def_readwrite("obj", &test_param::obj)
.def(const_self == const_self)
];
object tabc, zzk, zzv;
test_param tp;
tp.obj = 123456;
tabc = newtable(L);
// o k v
settable( tabc, tp, 5);
iterator zzi(tabc), end;
std::cerr << "value = " << *zzi << "\n";
zzk = zzi.key();
// o k v
settable( tabc, tp, 6);
settable( tabc, zzk, 7);
for (zzi = iterator(tabc); zzi != end; ++zzi)
{
std::cerr << "value = " << *zzi << "\n";
}
}
Notice how tabc[tp] first has the value 5 and then is overwritten with 7 when accessed through the key object. However, when accessed AGAIN through tp, a new entry gets created. This is why gettable() fails subsequently.
Thx,
David
Disclaimer: I'm not an expert on luabind. It's entirely possible I've missed something about luabind's capabilities.
First of all, what is luabind doing when converting test_param to a Lua key? The default policy is copy. To quote the luabind documentation:
This will make a copy of the parameter. This is the default behavior when passing parameters by-value. Note that this can only be used when passing from C++ to Lua. This policy requires that the parameter type has an accessible copy constructor.
In pratice, what this means is that luabind will create a new object (called "full userdata") which is owned by the Lua garbage collector and will copy your struct into it. This is a very safe thing to do because it no longer matters what you do with the c++ object; the Lua object will stick around without really any overhead. This is a good way to do bindings for by-value sorts of objects.
Why does luabind create a new object each time you pass it to Lua? Well, what else could it do? It doesn't matter if the address of the passed object is the same, because the original c++ object could have changed or been destroyed since it was first passed to Lua. (Remember, it was copied to Lua by value, not by reference.) So, with only ==, luabind would have to maintain a list of every object of that type which had ever been passed to Lua (possibly weakly) and compare your object against each one to see if it matches. luabind doesn't do this (nor do I think should it).
Now, let's look at the Lua side. Even though luabind creates two different objects, they're still equal, right? Well, the first problem is that, besides certain built-in types, Lua can only hold objects by reference. Each of those "full userdata" that I mentioned before is actually a pointer. That means that they are not identical.
But they are equal, if we define an __eq meta operation. Unfortunately, Lua itself simply does not support this case. Userdata when used as table keys are always compared by identity, no matter what. This actually isn't special for userdata; it is also true for tables. (Note that to properly support this case, Lua would need to override the hashcode operation on the object in addition to __eq. Lua also does not support overriding the hashcode operation.) I can't speak for the authors of Lua why they did not allow this (and it has been suggested before), but there it is.
So, what are the options?
The simplest thing would be to convert test_param to an object once (explicitly), and then use that object to index the table both times. However, I suspect that while this fixes your toy example, it isn't very helpful in practice.
Another option is simply not to use such types as keys. Actually, I think this is a very good suggestion, since this kind of light-weight binding is quite useful, and the only other option is to discard it.
It looks like you can define a custom conversion on your type. In your example, it might be reasonable to convert your type to a Lua number which will behave well as a table index.
Use a different kind of binding. There will be some overhead, but if you want identity, you'll have to live with it. It sounds like luabind has some support for wrappers, which you may need to use to preserve identity:
When a pointer or reference to a registered class with a wrapper is passed to Lua, luabind will query for it's dynamic type. If the dynamic type inherits from wrap_base, object identity is preserved.

libxmlrpc iterate through struct

I am implementing libxmlrpc into C++ project, anywayy, my RPC server has returned a struct with 52 member structs in them.
I do not know what the keys are as they are opaque references, so I cannot rely on them.
How can I iterate through the struct, I would have thought it was with the following code:
XmlRpcValue param_array = XmlRpcValue::makeArray();
param_array.arrayAppendItem(XmlRpcValue::makeString(this->sessionKey));
param_array.arrayAppendItem(XmlRpcValue::makeString("petabytes"));
XmlRpcValue result = ServerCall("Charter.getDataWarehouse.storage.capacity", param_array, url);
int index = 0;
while(index < result.structSize())
{
XmlRpcValue Data = result.getStruct();
//Would have thought it would work with this ;( shit documentation libxmlrpc has, grrrr
//Data.structGetKeyAndValue(index);
//This for example works, because I know the opaque reference, but in real life I wont
cout << Data.structGetValue("OpaqueRef:d4e60db6-2271-b0ac-d362-1b51220980af").structSize() << endl;
index++;
}
However, Data.structGetKeyAndValue(index) errors with:
no matching function for call to 'XmlRpcValue::structGetKeyAndValue(int&)
Which is fine, I understand it's not a public (well I think it's not a public member function) of xmlrpcvalue, however I cannot find anything that would allow me to do this.
Anyone have any experience with this?
Some quick Googling seems to indicate that you've got the function signature wrong:
void XmlRpcValue::structGetKeyAndValue(const int index, std::string& out_key, XmlRpcValue& out_value);