c++ - 内存重用不当导致的未定义行为

标签 c++ constructor

标准引用了下面的例子(3.8/7 N3797):

struct C 
{
    int i;
    void f();
    const C& operator=( const C& );
};

const C& C::operator=( const C& other) 
{
    if ( this != &other ) 
    {
        this->~C(); // lifetime of *this ends
        new (this) C(other); // new object of type C created
        f(); // well-defined
    }
return *this;
}

C c1;
C c2;
c1 = c2; // well-defined
c1.f(); // well-defined; c1 refers to a new object of type C

如果我们按如下方式实现operator=是否有UB:

const C& C::operator=( const C& other) 
{
    if ( this != &other ) 
    {                        // Note that there is no more explcicitly destructor call,
                             // since at the time of memory reusing the lifetime of 
                             // this is still going on
        new (this) C(other); // new object of type C created
        f(); // well-defined
    }
return *this;
}

相关引用是:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object

没有规则:“在对象占用的存储位置创建新对象”。 同时,我们有一个适用于 const 对象的规则。很明显:

第 3.8/9 节:

Creating a new object at the storage location that a const object with static, thread, or automatic storage duration occupies or, at the storage location that such a const object used to occupy before its lifetime ended results in undefined behavior.

最佳答案

相关规则是这样的:

3.8/4 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.

你的例子,正如所写的那样,是合法的,因为 C 有一个普通的析构函数。

关于c++ - 内存重用不当导致的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25757677/

相关文章:

c++ - 在 iOS 上 boost ASIO 错误 "Host not found"

c++ - dll中的xmlrpc服务器,向自己发送信号?

C# 对象初始化选项

c++ - 禁用非 POD 类的默认构造函数

python - lxml objectify 不会调用自定义元素类的构造函数

c++ - 返回值复制问题(以改进调试时间)——这里的解决方案是什么?

c++ - 在我的应用程序中需要 >=GTK 3.16。如何分配?

c++ - 模板参数的隐式转换规则

Kotlin 数据类二级构造函数初始化 block

c++ - 表初始化列表取 int,在用户定义的类中