The reference will exist for the entire lifetime of container
, but the object being referenced will exist only for the lifetime of that object. In this case, you have bound your reference to a temporary object with automatic storage allocation ("stack allocation", if you will, although that isn't C++ nomenclature). Therefore, you cannot expect the temporary to exist beyond the statement in which it was written (as it goes out of scope immediately after the call to the constructor for container
). The best way to deal with this is to use a copy, instead of a reference. Since you are using a const reference, anyway, it will have similar semantics.
You should redefine your class as:
template<typename T>
class container
{
public:
container(const T& first, const T& second) : first(first), second(second) {}
private:
const T first;
const T second;
};
Alternatively, you could give your objects a name to prevent them from going out of scope:
adaptor first;
adaptor second;
container c(first,second);
However, I don't think this a good idea, since a statement such as return c
is invalid.
Edit
If your goal is to share objects in order to avoid the cost of copying, then you should consider using smart pointer objects. For example, we can redefine your object using smart pointers as follows:
template<typename T>
class container
{
public:
container(const boost::shared_ptr<const T>& first, const boost::shared_ptr<const T>& second) : first(first), second(second) {}
private:
boost::shared_ptr<const T> first;
boost::shared_ptr<const T> second;
};
You can then use:
boost::shared_ptr<const adaptor> first(new adaptor);
boost::shared_ptr<const adaptor> second(new adaptor);
container<adaptor> c(first,second);
Or, if you want to have mutable copies of first and second locally:
boost::shared_ptr<adaptor> first(new adaptor);
boost::shared_ptr<adaptor> second(new adaptor);
container<adaptor> c(boost::const_pointer_cast<const adaptor>(first),boost::const_pointer_cast<const adaptor>(second));