rvalue reference factory?
{ Please limit your text to fit within 80 columns, preferably around 70,
so that readers don't have to scroll horizontally to read each line.
This article has been reformatted manually by the moderator. -mod }
Is it possible in c++11 to have a factory function that returns
rvalue references of base class types?
I didn't succeed this the example below.
It generates core dump on linux.
My "real" application - where i extracted the example from -
does a bit different:
pure virtual method called
terminate called without an active exception
---------------- test.cc -----------------------------
#include <string>
#include <iostream>
#include <stdexcept>
#include <memory>
class BaseClass
{
public:
BaseClass()
{ };
virtual ~BaseClass()
{ };
virtual std::string const & GetId(void) = 0;
virtual BaseClass && build(void) = 0;
};
class Derived1 : public BaseClass
{
public:
Derived1()
: BaseClass()
{ };
~Derived1()
{ }
std::string const & GetId(void)
{
static std::string const & id("Derived1");
return id;
}
Derived1 && build(void)
{
return std::move(Derived1());
}
};
class Derived2 : public BaseClass
{
public:
Derived2()
: BaseClass()
{ };
~Derived2()
{ }
std::string const & GetId(void)
{
static std::string const & id("Derived2");
return id;
}
Derived2 && build(void)
{
return std::move(Derived2());
}
};
class Factory
{
public:
static BaseClass && build(std::string const & id)
{
if (0 == id.compare("Derived1"))
{
static Derived1 derived1;
return std::move(derived1.build());
}
else if (0 == id.compare("Derived2"))
{
static Derived2 derived2;
return std::move(derived2.build());
}
else
{
throw std::runtime_error("invalid type");
}
}
};
int main(int argc, char** argv)
{
try
{
#if 1
// this does not work
BaseClass && baseClass(std::move(Factory::build("Derived1")));
BaseClass * ptr = &baseClass;
#else
// this works
Derived1 && derived1(std::move(Derived1().build()));
BaseClass * ptr = &derived1;
#endif
std::cout << "ID = " << ptr->GetId() << std::endl;
}
catch (std::exception & e)
{
std::cerr << "exception: " << e.what() << std::endl;
}
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]