我正在使用unique_ptr,我得到了一些奇怪的结果。 这是代码:
class Sniffer { public: Sniffer() { cout << "Sniffer()" << endl; s = "String!"; } void operator()() { cout << "operator()(): " << s << endl; } ~Sniffer() { cout << "~Sniffer()" << endl; } private: string s; }; int main() { cout << "Begin scope!" << endl; { Sniffer& h = *std::unique_ptr<Sniffer>(new Sniffer()); // 1 //std::unique_ptr<Sniffer> p(new Sniffer()); // 2 //Sniffer& h = *p; // 2 h(); } cout << "End scope!" << endl; return 0; }我不明白为什么使用代码“1”,析构函数在operator()()之前调用,而“End Scope!”根本不打印。 代码不会崩溃,它会执行到最后一行,我得到的输出是:
Begin scope! Sniffer() ~Sniffer() operator()(): Press any key to continue . . .另一方面,代码“2”表现如预期:
Begin scope! Sniffer() operator()(): String! ~Sniffer() End scope! Press any key to continue . . .我使用引用的原因仅仅是因为我感觉h()感觉比(*p)()或p->operator()()更自然。 谢谢。
I'm using unique_ptr, and I'm getting some odd results. This is the code:
class Sniffer { public: Sniffer() { cout << "Sniffer()" << endl; s = "String!"; } void operator()() { cout << "operator()(): " << s << endl; } ~Sniffer() { cout << "~Sniffer()" << endl; } private: string s; }; int main() { cout << "Begin scope!" << endl; { Sniffer& h = *std::unique_ptr<Sniffer>(new Sniffer()); // 1 //std::unique_ptr<Sniffer> p(new Sniffer()); // 2 //Sniffer& h = *p; // 2 h(); } cout << "End scope!" << endl; return 0; }I don't understand why with code "1", the destructor gets called before operator()(), and "End Scope!", is not printed at all. Code doesn't crash, it executes till the last line, the output I get is:
Begin scope! Sniffer() ~Sniffer() operator()(): Press any key to continue . . .On the other side code "2" behaves as expected:
Begin scope! Sniffer() operator()(): String! ~Sniffer() End scope! Press any key to continue . . .The reason I'm using a reference is only because I felt h() felt more natural than (*p)() or p->operator()(). Thanks.
最满意答案
在这个声明中
Sniffer& h = *std::unique_ptr<Sniffer>(new Sniffer());创建一个std::unique_ptr<Sniffer>类型的临时对象,该对象在语句执行结束时被销毁。
因此,引用h在代码块的范围内无效。
在这个声明中
std::unique_ptr<Sniffer> p(new Sniffer()); // 2对象p被创建并将一直存在,直到代码块结束。 所以参考h
Sniffer& h = *p;在此范围内有效。
In this statement
Sniffer& h = *std::unique_ptr<Sniffer>(new Sniffer());a temporary object of type std::unique_ptr<Sniffer> is created that is destroyed at the end of execution of the statement.
Thus reference h is invalid in the scope of the code block.
In this statement
std::unique_ptr<Sniffer> p(new Sniffer()); // 2object p is created and will be alive until the end of the code block. So reference h
Sniffer& h = *p;will be valid in this scope.
更多推荐
发布评论