gpt4 book ai didi

C++ 是否使用放置新的未定义行为两次构造对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:39 24 4
gpt4 key购买 nike

我遇到了一些令我震惊的代码。本质上它遵循这种模式:

class Foo
{
public:
//default constructor
Foo(): x(0), ptr(nullptr)
{
//do nothing
}

//more interesting constructor
Foo( FooInitialiser& init): x(0), ptr(nullptr)
{
x = init.getX();
ptr = new int;
}
~Foo()
{
delete ptr;
}

private:
int x;
int* ptr;
};


void someFunction( FooInitialiser initialiser )
{
int numFoos = MAGIC_NUMBER;
Foo* fooArray = new Foo[numFoos]; //allocate an array of default constructed Foo's

for(int i = 0; i < numFoos; ++i)
{
new( fooArray+ i) Foo( initialiser ); //use placement new to initialise
}

//... do stuff

delete[] fooArray;
}

此代码已在代码库中存在多年,似乎从未引起过问题。这显然是一个坏主意,因为有人可以更改默认构造函数来分配不期望的第二个构造。简单地用等效的初始化方法替换第二个构造函数似乎是明智的做法。例如。

void Foo::initialise(FooInitialiser& init)
{
x = init.getX();
ptr = new int;
}

虽然仍然存在可能的资源泄漏,但至少防御性程序员可能会考虑以正常方法检查先前的分配。

我的问题是:

像这样构造两次实际上是未定义的行为/被标准禁止还是仅仅是一个坏主意?如果有未定义的行为,您能否引用或指出我在标准中查看的正确位置?

最佳答案

通常,以这种方式处理新放置不是一个好主意。从第一个 new 开始调用初始化程序,或者调用初始化程序而不是 placement new 都被认为是比您提供的代码更好的形式。

但是,在这种情况下,在现有对象上调用 placement new 的行为是明确定义的。

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

所以当这种情况发生时:

Foo* fooArray = new Foo[numFoos];   //allocate an array of default constructed Foo's

for(int i = 0; i < numFoos; ++i)
{
new( fooArray+ i) Foo( initialiser ); //use placement new to initialise
}

placement new 操作将结束那里的 Foo 的生命周期,并在它的位置创建一个新的。在许多情况下,这可能很糟糕,但考虑到析构函数的工作方式,这会很好。

在现有对象上调用 placement new 可能是未定义的行为,但这取决于特定对象。

这不会产生未定义的行为,因为您不依赖于析构函数产生的“副作用”。

对象的析构函数中唯一的“副作用”是 delete 包含的 int 指针,但在这种情况下,该对象永远不会处于可删除状态当放置 new 被调用时。

如果包含的 int 指针可能等于 nullptr 以外的值并且可能需要删除,则调用放置 new 在现有对象上会调用未定义的行为。

关于C++ 是否使用放置新的未定义行为两次构造对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com