Unique Pointers
Jun 24, 2015 at 3:14am UTC
Hi, I'm trying to get some practice with smart pointers (specifically unique_ptr), but my compiler doesn't support C++14 so I cant use make_unique, which is what I think I'd need to use. Are there any alternatives to make_unique that work in C++11? Thanks in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <memory>
using namespace std;
unique_ptr<SavingsAccount> unqSaPtr = nullptr ;
string uName, uPwd;
int main()
{
bool done = false ;
while (!done)
{
int decision = showMenuOptions();
switch (decision)
{
case 1:
cout << "Enter your name: " ;
getline(cin, uName);
// Error is here.. alternatives to make_unique??
unqSaPtr(new SavingsAccount(uName, uPwd));
break ;
case 2:
// ...
break ;
case 3:
done = false ;
break ;
default :
cerr << "Invalid option." << endl;
continue ;
}
}
}
If any other code is needed for reference, just let me know.
Jun 24, 2015 at 7:02am UTC
1 2 3 4 5
template <typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
Jun 24, 2015 at 8:01am UTC
Use the reset(...) member of unique_ptr: unqSaPtr.reset (new SavingsAccount(uName, uPwd));
Topic archived. No new replies allowed.