提问人:cmasterisk 提问时间:6/5/2020 更新时间:6/6/2020 访问量:42
堆栈分配的类类型。为什么两个 ID 实例的地址相同?
Class type for stack allocation. Why the address for both ID instances are the same?
问:
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;
}
答:
1赞
cigien
6/5/2020
#1
在此函数中:
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
评论
0赞
cigien
6/6/2020
@cmasterisk没问题。另请查看问题评论中提供的链接。那里有很多有用的信息。此外,如果它回答了您的问题,请考虑接受答案。
评论