堆栈分配的类类型.为什么两个 ID 实例的地址相同?

Class type for stack allocation. Why the address for both ID instances are the same?

本文关键字:实例 ID 地址 两个 分配 类型 为什么 堆栈      更新时间:2023-10-16
class ID
{
public:
ID(const std::string& name) :
name_(name) {}
// explicit copy constructor as my first solution but gave me same address
ID(const ID& other)
{ name_ = other.getName(); } 
std::string getName() const
{ return name_; }
private:
std::string name_;
};
ID createID(const std::string& name)
{
ID id(name); // new stack allocation for id
std::cout << "ID addr: " << &id << "n";
return id;
}
int main()
{
ID my_id = createID("John"); // new stack allocation for my_id
std::cout << "my_id addr: " << &my_id << "n";
std::cout << my_id.getName() << std::endl;
}

平台:Ubuntu终端(Windows的Ubuntu子系统(

编译:g++ 文件.cpp

输出:"ID 之间的地址相同">

输出不应该提供不同的堆栈地址吗?

我尝试使用原始整数(而不是 ID 类类型(复制它,它为不同的实例输出不同的地址。

int func(int i)
{
int j = i;
std::cout << "i addr: " << &i << std::endl;
std::cout << "j addr: " << &j << std::endl;
return i;
}
int main()
{
int x = 10;
std::cout << "X addr: " << &x << std::endl;
int y = func(x);
std::cout << "Y addr: " << &y << std::endl;
}

在此函数中:

ID createID(const std::string& name)
{
ID id(name); // new stack allocation for id
std::cout << "ID addr: " << &id << "n";
return id;
}

对于呼叫:

ID my_id = createID("John"); // new stack allocation for my_id

编译器似乎正在执行 NRVO(名为返回值优化(。所以函数中没有实际的id复制到变量my_id,也没有单独的分配。

相反,此副本被省略,您会看到相同的地址。所以评论// new stack allocation for my_id实际上是不正确的。

请注意,NRVO 不能保证发生,因此不应依赖此行为。编译器可以制作副本,从而产生不同的地址。实际上,这就是func返回int的示例中发生的情况。由于这是一种便宜的复制类型,编译器实际上会制作副本,并且您会看到不同的地址。