std::make_shared not working, but creating the pointer using "new" works fine - c++

I am currently making a GUI system for my game engine. I tried to create a shared pointer for one of the components "GUImovingbar" using std::make_shared() but got the following error when compiling
'std::shared_ptr<_Other> std::make_shared(_Types &&...)': could not deduce template argument for '_Types &&...' from 'initializer list'
However, when I used the exact same inputs to create a new pointer, it compiled fine with no errors. This struck me as a bit odd. What am I missing here?
Code using std::make_shared():
this->playerhullbar = std::make_shared<GUImovingbar>(
"right",
{ 50,hully }, //scoords
globalguitextures[findStringSrdPointerPairVectElement(globalguitextures, "barbackground")].second,
{ 0,static_cast<double>(maxplayerhullint),static_cast<double>(maxplayerhullint) },
{ 50,hully,250, hully,2,100 },//for int vector input ("bsbebdbc"): 1 barxstart, 2 y , 3 barendx, 4 y, 5 distance between bars in px, 6 bar count
{ 0,255,0 },
bartextvect
);
Above causes error:
'std::shared_ptr<_Other> std::make_shared(_Types &&...)': could not deduce template argument for '_Types &&...' from 'initializer list'
The following causes no errors at all:
std::shared_ptr<GUImovingbar> newptr(new GUImovingbar(
"right",
{ 50,hully}, //scoords
globalguitextures[findStringSrdPointerPairVectElement(globalguitextures, "barbackground")].second,
{ 0,static_cast<double>(maxplayerhullint),static_cast<double>(maxplayerhullint) },
{ 50,hully,250, hully,2,100 },//for int vector input ("bsbebdbc"): 1 barxstart, 2 y , 3 barendx, 4 y, 5 distance between bars in px, 6 bar count
{ 0,255,0 },
bartextvect)
);
this->playerhullbar = newptr;

As a template function, std::make_shared tries to find the appropriate constructor for your class given the parameters it has. Since you've given it initializer lists (the stuff in brackets), it is confused about what type those lists are supposed to initialize, and it thus can't find the appropriate constructor. However, when you use the constructor proper, ambiguity is removed, since thanks to the parameters' position the compiler knows what type the lists are supposed to initialize, and it converts them accordingly.
If you still want to use std::make_shared, you'll have to disambiguate the types of the initializer lists by putting them before the list :
this->playerhullbar = std::make_shared<GUImovingbar>(
"right",
Scoords { 50,hully },
globalguitextures[findStringSrdPointerPairVectElement(globalguitextures, "barbackground")].second,
Rect { 0,static_cast<double>(maxplayerhullint),static_cast<double>(maxplayerhullint) },
std:vector<int> { 50,hully,250, hully,2,100 },
Color { 0,255,0 },
bartextvect
);
(or, if you have an old compiler, use the former syntax with parentheses as well : std:vector<int>({ 50,hully,250, hully,2,100 }))

The problems are the aggregate initializations that you're doing in the make_shared call. If you create an object with new GUImovingbar(...) you are directly calling the constructor and thus, the compiler knows exactly which argument is of which type. This enables you to aggregate initialize said arguments.
However, if you call make_shared all arguments must be deduced from the value that you pass to the function (because it's a template). This would basically be like this:
auto x = {10, "hello", 4};
How should the compiler know what type this actually is?
If you still want to use make_shared you have to explicitly initialize the types with their names.

Related

Was it possible to get a pointer to member from an instance of an object?

I was porting some legacy code to VS 2015 when this compiler error halted the build:
error C3867: 'OptDlg::GetFullModel': non-standard syntax; use '&' to create a pointer to member
Going to the corresponding file and line, I saw this:
Manager mgr = GetDocument()->GetManager();
OptDlg dlg;
...
mgr->SetFullModel(dlg.GetFullModel);
if ( dlg.GetFullModel )
mgr->SetSymm(...
GetFullModeland SetFullModel are the getter/setter pair for a member variable in two different classes:
class Manager {
...
bool GetFullModel() { return m_bFullModel; }
void SetFullModel(bool bFlag) { m_bFullModel = bFlag; }
....
};
class OptDlg {
...
void GetFullModel() { return m_bFullModel; }
void SetFullModel(bool bValue) { m_bFullModel = bValue; if ( bValue ) m_bInside = 0;}
Yep, something's wrong. Was dlg.GetFullModel supposed to be a pointer to a member function? I thought those use the class name, not an instance. Not to mention what that would mean for execution semantics...
C++ is still relatively new to me, so I tried Google. It had a lot on function pointers, but they all looked different from what I had:
&OptDlg::GetFullModel // Standard-compliant
vs
OptDlg::GetFullModel // The "normal" way to mess up getting a pointer to member, it seems
vs
dlg.GetFullModel // ?
Is dlg.GetFullModel just another way of getting a pointer to member function? If not, what is the "standard C++ version", if there is one? Is this just another one of those VS 6 "extensions"?
&OptDlg::GetFullModel // Standard-compliant
If your parameter types were supposed to be taking member functions, that's what you'd use. But they take booleans. It looks like you're just missing parentheses on your function calls, and it should be:
mgr->SetFullModel(dlg.GetFullModel());
if (dlg.GetFullModel())
mgr->SetSymm(...
Probably someone was ignoring warnings (or didn't have them on) and hence a pointer value (being produced through whatever shady means) was always being interpreted as non-NULL, hence boolean true.
Is this just another one of those VS 6 "extensions"?
It would appear to be the case, although this comment is the only documented evidence I can find it was an intentional/advertised "feature". Don't see any formal announcement of it being added or taken out.
It strongly looks to me like someone mis-typed dlg.GetFullModel() (which would call the function), not that they were trying to get a member function pointer.
Presumably the legacy compiler let it slide, taking the address of the function without using & and converting the non-null function pointer to bool (with value true) to pass into the set function.

C++ std::sort custom compare function referencing to another list

I am a beginner in C++ and I don't know nor can find the way to address my problem.
I'm trying to sort my vector in an unusual way and fail to do so.
pointsToVisit - list of Point objects that can have their start time and end time.
visitedPoints - list of indexes of Point objects from pointsToVisit vector
I'd like to sort my visitedPoints vector by values of respective Points
BeeHive
std::vector<Point> pointsToVisit;
std::vector<Route> routes;
Route
std::vector<int> visitedPoints;
My attemp is below:
bool BeeHive::isPointsVisitStartPrior (int i, int j) { return (pointsToVisit.at(i).startTime<pointsToVisit.at(j).startTime); }
Route BeeHive::sortRouteByStartTime(int routeIndex){
Route route2 = Route();
route2.setStartTime(routes.at(routeIndex).getStartTime());
route2.setVisitedPoints(routes.at(routeIndex).getVisitedPoints());
std::sort(route2.getVisitedPoints().begin()+1, route2.getVisitedPoints().end(), isPointsVisitStartPrior);
evaluateRoute(route2);
return route2;
}
And I get such errors:
Error 5 error C3867: 'BeeHive::isPointsVisitStartPrior': function call missing argument list; use '&BeeHive::isPointsVisitStartPrior' to create a pointer to member c:\vrp projekt\vrp\vrp\beehive.cpp 193 1 VRP
Error 6 error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided c:\vrp projekt\vrp\vrp\beehive.cpp 193 1 VRP
Example by which I tried to do my work is under this address: http://www.cplusplus.com/reference/algorithm/sort/
I'll be thankful for any help received.
Might it be possible, that creating bubble sort for my own purposes will substitute std::sort() decently?
isPointsVisitStartPrior is a member function, this cannot be used directly in sort. You have to either use a global function or a function-object.
If you have access to C++ 11 features, you can use a lambda:
std::sort(route2.getVisitedPoints().begin()+1, route2.getVisitedPoints().end(),
[&](int i, int j){ return isPointsVisitStartPrior(i, j); });
You can also make a functor object with an operator(), something like
class VisitedPointsCompararer {
public:
VisitedPointsCompararer(const std::vector<Point>& pointsToVisit): pointsToVisit(pointsToVisit) {
}
bool operator() (int i, int j) {
return pointsToVisit.at(i).startTime < pointsToVisit.at(j).startTime;
}
...
private:
const std::vector<Point>& pointsToVisit;
}
isPointsVisitStartPrior(int, int) is a member function. A such, while it looks like it takes two arguments, it really implicitly takes three: it also needs a BeeHive* on which to operate (the this pointer).
What you need to do is "bind" the BeeHive* to the call:
using namespace std::placeholders;
std::sort(route2.getVisitedPoints().begin()+1,
route2.getVisitedPoints().end(),
std::bind(&BeeHive::isPointsVisitStartPrior, this, _1, _2)
// ^^^^^^^^^ without C++11, there's also boost::bind
);
That will save off this as the first argument in the call to the three-argument function, and forward the next two arguments you call it with into the next two slots.
This is logically equivalent to:
std::sort(route2.getVisitedPoints().begin()+1,
route2.getVisitedPoints().end(),
[this](int i, int j){ return isPointsVisitStartPrior(i, j); }
);
Though with the lambda, the compiler may be able to inline the call for you.

Creating an auto_ptr with 2 arguments

Hi I have a compile error when I run this code:
std::auto_ptr<MyDisplay> m_display =
std::auto_ptr<MyDisplay>(new MyDisplay(this, m_displayController));
The error is this one:
error C2664: 'MyDisplay::MyDisplay(DemoWindow *,DisplayController*)':
cannot convert parameter 2 from 'std::auto_ptr<_Ty>' to 'DisplayController*'
However when I pass only one argument the code is correct:
std::auto_ptr<DisplayController> m_displayController =
std::auto_ptr<DisplayController>(US_NEW(DisplayController, this));
What is the proper way to create the pointer in the auto_ptr with 2 arguments?
From the error message, it appears that m_displayController is an std::auto_ptr<DisplayController>, while the MyDisplay constructor expects a DisplayController*.
Try :
std::auto_ptr<MyDisplay> m_display =
std::auto_ptr<MyDisplay>(new MyDisplay(this, m_displayController.get()));
or better yet, make the constructor compatible with std::auto_ptr<DisplayController>.
As an aside : the choice of std::auto_ptr here is probably not the best. You might want to read up on the different types of smart pointers, and the different behaviors they have.
I'd like to clarify your idea of creating the auto pointer, which I hope will help.
Your goal here is to create an auto_ptr holding a DisplayController*. You could write
m_displayController = std::auto_ptr<DisplayController>( new DisplayController(x, y) );
Or have a function that returns a pointer, like this :
m_displayController = std::auto_ptr<DisplayController>( US_NEW(x,y) );
You can check out a simple example here.

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.

Structure Initialization Unmatched variables

I am confused as to what this is doing:
#define AIR_LP 1
tw_lptype airport_lps[] = {
{
AIR_LP, sizeof(Airport_State),
(init_f) Airport_StartUp,
(event_f) Airport_EventHandler,
(revent_f) Airport_RC_EventHandler,
(final_f) Airport_Statistics_CollectStats,
(statecp_f) NULL
},
{ 0 },
};
and
struct tw_lptype
{
init_f init;
event_f event;
revent_f revent;
final_f final;
map_f map;
size_t state_sz;
};
I guess I am getting confused by the first two variables in the structure declaration AIR_LP and sizeof(Airport_state), I understand what all the rest is doing, so if someone can just give me some info as to what those two parts are going to that would be great.
It's difficult to answer your question without knowing the types involved. The problem you are having is that your initialization has 7 attributes to the structure when your structure has 6. The AIR_LP, sizeof(Airport_State), are separate elements unlike the rest of the initialization which consists of a type cast followed by a value.