gpt4 book ai didi

c++ - 可以在调用构造函数之前完成赋值吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:01:30 25 4
gpt4 key购买 nike

What's wrong with this fix for double checked locking? 的评论说:

The issue is that the variable may be assigned before the constructor is run (or completes), not before the object is allocated.

让我们考虑代码:

A *a;

void Test()
{
a = new A;
}

为了进行更正式的分析,让我们将 a = new A 拆分为几个操作:

void *mem = malloc(sizeof(A)); // Allocation
new(mem) A; // Constructor
a = reinterpret_cast<A *>(mem); // Assignment

上面引用的评论是真的吗?如果是,在什么意义上? Constructor 可以在Assignment 之后执行吗?如果可以,当因为 MT 安全需要保证顺序时,可以做些什么来反对它?

最佳答案

问题不在于代码执行时,而在于写顺序。

假设:

A()
{
member = 7;
}

然后:

singleton = new A()

这导致代码执行分配、写入内存(成员),然后写入另一个内存位置(单例)。某些 CPU 可以对写入进行重新排序,以便在写入单例之前,对成员的写入是不可见的——本质上,在系统中其他 CPU 上运行的代码可以查看写入单例的内存,但是成员是不是。

关于c++ - 可以在调用构造函数之前完成赋值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1009691/

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