公共成员变量何时死亡?

时间:2016-04-18 20:47:47

标签: c++ destructor

我有以下C ++类:

class DEF
{
   //...
}

class ABC
{
   public:
      DEF my_def;
      ~ABC();
   //...
}

某处:

ABC* abc = new ABC(...);
delete abc;

我的问题:

调用delete abc后是否可以访问my_def?在删除后abc->my_def.somefunc() 安全吗?   -

1 个答案:

答案 0 :(得分:4)

不,在let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { // Don't put other code before this next line, it is defining the closure we just started with the "{" (data, response, error) -> Void in // This is where the closure body begins print(NSThread.isMainThread()) // false (unless you've set the delegate queue to be the main queue) // Example of processing the return value let dataString = NSString.init(data: data!, encoding: NSUTF8StringEncoding) print(dataString) // Okay to do work with this here, but don't do any UI work. // Jump back over to the main queue to do any UI updates // UI updates must always be done on the main queue dispatch_async(dispatch_get_main_queue(), { print(NSThread.isMainThread()) // true (we told it to execute this new block on the main queue) // Execute the code to update your UI (change your view) from here myCoolUIUpdatingMethod(dataString) }); // anything down here could be executed before the dispatch_async block completes // dispatch_sync would block this thread until its block completes }); // run the task task.resume() // your program's main thread will not be blocked while the load is in progress 的析构函数运行后,其成员将按其声明的相反顺序销毁。删除abc后,其所有内存都将被释放。这包括您示例中的abc

也许这个问题对您有用:What is a smart pointer and when should I use one?

附录:C ++的一个主要问题是undefined behavior。如果在此期间内存未被重用,则use-after-free等编程错误可能会在80%的时间内起作用。但是你可能会覆盖不相关的内存和/或允许读取外来数据。这是一个严重的安全问题,崩溃的程序是你现在最好的希望。