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

问题描述 投票:0回答:1
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

输出:“ 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;
}
c++ memory-management stack-allocation
1个回答
0
投票

在此功能:

© www.soinside.com 2019 - 2024. All rights reserved.