I read somewhere if you want to return a local variable via reference do it via smart pointers and the motivation behind this code is exacttly the same i want to return a Test
class variable without it copy being created or in other words Return a local variable with reference
. But Everytime return statement executes it calls the destructor . Can anybody help me achieveing my goal via smart pointer . Here is my sample code .
#include <iostream>
#include <memory>
#include <unistd.h>
class Test {
public:
Test() {
std::cout << "I am the constructor of A \n";
}
~Test() {
std::cout << "I am the Distructor of A \n";
}
};
std::unique_ptr<Test> num() {
Test obj;
std::unique_ptr<Test> newInt = std::make_unique<Test>(obj);
return newInt;
};
int main() {
std::unique_ptr<Test> ptr = num();
sleep(12);
}