简体   繁体   English

C++中返回指针的函数

[英]Function that returns a pointer in C++

I've started learning about pointers and I ended up with a question over functions and pointers.我已经开始学习指针,最后我提出了一个关于函数和指针的问题。 I created a simple function that should return the address/pointer of an Integer type.我创建了一个简单的函数,它应该返回整数类型的地址/指针。 However, after printing the address using "&" it differs from what the function returns me.但是,使用“&”打印地址后,它与函数返回的地址不同。 What am I missing here?我在这里缺少什么?

int* address_ofInt(int a) {
        return &a;
}
int main() {
        int foo = 124;
        std::cout << &foo << std::endl;
        std::cout << address_ofInt(foo) << std::endl;

        return 0;
}
// It outputs
// 0x7ffee2434b08
// 0x7ffee2434acc
int* address_ofInt(int a) {

This is called "passing by value" in C++.这在 C++ 中称为“按值传递”。 This means that whatever the caller passes, as a parameter to the function, effectively a copy is made, and that's what this a is.这意味着无论调用者传递什么,作为函数的参数,都会有效地创建一个副本,这就是a的含义。 This function can modify this a , and it will have no effect on the original parameter, since it's just a copy.这个函数可以修改这个a ,它不会影响原始参数,因为它只是一个副本。

This a is a completely independent object or variable, and its address is completely different and has nothing to do with the address of whatever was passed to this function.这个a是一个完全独立的对象或变量,它的地址完全不同,与传递给这个函数的任何地址无关。

 return &a;

This function returns the address of its by-value parameter.此函数返回其按值参数的地址。 Which is completely meaningless, since once the function returns its by-value parameter no longer exist.这是完全没有意义的,因为一旦函数返回它的按值参数就不再存在。 It was a copy of the original parameter that was passed to this function, and it gets automatically destroyed.它是传递给此函数的原始参数的副本,它会自动销毁。 It is no more.已经不复存在了。 It ceased to be.它不再是。 It joined the choir invisible.它加入了隐形合唱团。 It's pining for the fjords.它渴望峡湾。 It is an ex-variable.它是一个前变量。 The caller gets a pointer to a destroyed object, and attempting to dereference the pointer results in undefined behavior.调用者获得一个指向被销毁对象的指针,并试图取消引用该指针会导致未定义的行为。

Your C++ textbook will have a chapter that explains what references are, how they work in C++, and how to pass parameters to the function by reference instead of by value .您的 C++ 教科书将有一章解释什么是引用、它们在 C++ 中的工作方式以及如何通过引用而不是通过值将参数传递给函数。 And in that case modifying a will actually modify the original object that was the parameter to this function.在这种情况下,修改a实际上会修改作为此函数参数的原始对象。 If you do that you will discover that both pointers will be the same, since the function parameter will be a reference to the original parameter that was passed to it.如果这样做,您会发现两个指针是相同的,因为函数参数将是传递给它的原始参数的引用 See your C++ textbook for more information.有关更多信息,请参阅您的 C++ 教科书。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM