Class 堆栈分配类型。为什么两个 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++ file.cpp

输出:"Same address between IDs"

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

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

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(名为 return 值优化)。所以函数中没有实际拷贝id到变量my_id,也没有单独分配

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

请注意,NRVO 不一定会发生,因此您不应依赖此行为。编译器 可以 进行复制,从而产生不同的地址。事实上,这就是 func return 和 int 示例中发生的情况。由于这是一种复制成本低的类型,编译器实际上进行了复制,您会看到不同的地址。