std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.
You need to initialize it through the member-initializer list:
A::A(std::string filename) :
file(new std::ifstream(filename));
{ }
Your example was an attempt to call operator ()
on a unique_ptr
which is not possible.
Update: BTW, C++14 has std::make_unique
:
A::A(std::string filename) :
file(std::make_unique<std::ifstream>(filename));
{ }
You can do it like this:
A:A(std::string filename)
: file(new std::ifstream(filename.c_str())
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With