e******d 发帖数: 310 | 1 Sorry for no Chinese input.
I failed in Bloomberg on-site interview for a senior software development position. The following two questions may be helpful
1. In which cases can the destructor of a class not be called?
2. In a try block, we allocate some memory ; then an exception is thrown.
How can we get the allocated memory released before we jump to catch block to process the exception? |
z****e 发帖数: 2024 | 2 1. placement new
2. wrap the pointer into a class |
p**********s 发帖数: 115 | |
e******d 发帖数: 310 | 4
Why? Can u explain? Thx
How about the following two cases
A. Destructor defined as private
B. New an object, then an exception is thrown.
Auto_ptr?
【在 z****e 的大作中提到】 : 1. placement new : 2. wrap the pointer into a class
|
a*****k 发帖数: 704 | 5 exception is a good answer.
I don't think A is a good answer. if destructor is private,
then you cannot compile.
another case I can think of is "no virtual destructor".
【在 e******d 的大作中提到】 : : Why? Can u explain? Thx : How about the following two cases : A. Destructor defined as private : B. New an object, then an exception is thrown. : : Auto_ptr?
|
z****e 发帖数: 2024 | 6 what are u talking about?
there are millions of ways for a class with private destructor to
instantiated, used, then destructed.
【在 a*****k 的大作中提到】 : exception is a good answer. : I don't think A is a good answer. if destructor is private, : then you cannot compile. : another case I can think of is "no virtual destructor".
|
z****e 发帖数: 2024 | 7 oops, i misread the question, the question is "not" be called. I though it
was "should be called".
hehe, even public virtual dtor can not be called if you copy it improperly.
【在 e******d 的大作中提到】 : : Why? Can u explain? Thx : How about the following two cases : A. Destructor defined as private : B. New an object, then an exception is thrown. : : Auto_ptr?
|
e******d 发帖数: 310 | 8 For placement new, we can call the destructor.
I shall post an example later which covers our prior discussions. It is
hard to type code by phone |
e******d 发帖数: 310 | 9 Some code used to verify the above discussions. If you find the code is not correct, please revise it. Thank you.
=========================================================
#include "stdio.h"
#include
class MyException
{
public:
MyException(){
printf("Constructor MyException() is called. \n");
}
~MyException(){
printf("Destructor ~MyException() is called. \n");
}
private:
};
class A{
public:
A()
{
printf("A() is called \n");
}
~A |
a****n 发帖数: 1887 | 10 1. In which cases can the destructor of a class not be called?
1)ctor 抛出异常
2)该class 为父类且析构函数非虚, delete 子类指针的情况
3)当然, 你用了new, 没用delete
4)用了placement new 没使用显示desctor
估计考官想听到1) |