Saj*_*jib 1 c++ smart-pointers unique-ptr
我有一个代码块,我正在使用unique_ptr.
class Abc {
public:
std::string msg;
Abc(std::string m) {
msg = m;
std::cout << "Constructor: " << msg << std::endl;
}
~Abc() {
std::cout << "Destructor: " << msg << std::endl;
}
};
int main() {
auto p = std::make_unique<Abc>(Abc(__func__));
}
Run Code Online (Sandbox Code Playgroud)
但是析构函数被调用了两次。有没有办法让它只调用一次析构函数?
您首先构造一个临时Abc(即Abc(__func__)),然后将其传递给std::make_unique,它Abc从临时构造底层(通过 的移动构造函数Abc);即Abc构造了两个对象,然后也调用了两次析构函数。
你可以通过__func__向std::make_unique直接,即无需构建临时Abc从一开始。
auto p = std::make_unique<Abc>(__func__); // constructs Abc via Abc::Abc(std::string) directly
Run Code Online (Sandbox Code Playgroud)