如果我想在栈上已经创建的对象上放置新的对象:
struct s{
s() { std::cout << "C\n";}
~s() { std::cout << "D\n";}
};
int main() {
s s1[3];
for(int i=0; i< 3; ++i)
s* newS = new (&s1[i]) s();
}我得到了:
C
C
C
C
C
C
D
D
D所以我们没有为前3个对象获取析构函数,这安全吗?如果我们只是覆盖在堆/栈上分配的对象的内存,而这些对象不需要释放析构函数中的任何资源,这仍然是安全的吗?
发布于 2016-09-02 16:22:51
您的输出并不出乎意料-- 不会调用存储在您正在访问的内存位置中的任何潜在对象的析构函数。为了安全地使用placement new,您需要对占用您试图使用的内存位置的任何对象执行explictly invoke the destructor操作。
struct s
{
s()
{
std::cout << "C\n";
}
~s()
{
std::cout << "D\n";
}
};
int main()
{
// Three 's' instances are constructed here.
s s1[3];
// (!) You need to explicitly destroy the existing
// instances here.
for(int i = 0; i < 3; ++i)
{
s1[i].~s();
}
for(int i = 0; i < 3; ++i)
{
// Three 's' instances are constructed here.
s* newS = new(&s1[i]) s();
}
// Three 's' instances are destroyed here.
}输出:
C
C
C
D
D
D
C
C
C
D
D
Dhttps://stackoverflow.com/questions/39287330
复制相似问题