In C++11, I have a class with a function that returns a new instance of that class. My clearly incorrect assumption was that if I constructed a new instance and returned it by value, the new instance would stay in scope. But I've learned that what I'm correctly observing is that its being destroyed like any other local variable. EDIT: My question is, what do I need to add or change to make a function instantiate an object and return it (without having it preallocated and passed in as a parameter)?
EDIT2: I've added move and copy constructors, and tried explicitly calling new Thingy instead of just having an instance variable. Still no change in behavior. I see the copy constructor called and then the destructor called when I invoke the function.
template<typename T>
class Thingy {
public:
// Constructor
Thingy(unsigned n) {
n_ = n;
}
// Move constructor
Thingy<T>(Thingy<T> && obj) {
cout << "Move constructor\n";
this->n_ = obj.n_;
}
// Copy constructor
Thingy<T>(const Thingy<T>& copy) {
cout << "Copy constructor\n";
this->n_ = copy.n_;
}
// Destructor
~Thingy() {
cout << "Destructor\n";
}
Thingy<T> dosomething() {
// Thingy<T> thing(n_); <-- this goes out of scope
Thingy<T>* thing = new Thingy<T>(n_); // I was hoping this would stay in scope, but no
...
return thing;
}
private:
unsigned n_;
In my main code I basically do:
Thingy<mytype> mainthing(10);
Thingy<mytype> anotherthing = mainthing.dosomething();
I can see that the destructor is being called and anotherthing is garbage.
What am I doing wrong/missing? Thanks!