C++11 在函数中声明指针,C++;

C++11 在函数中声明指针,C++;,c++11,pointers,C++11,Pointers,在函数中注册新指针时会发生什么? 我承认,应该销毁指针的名称。 但是分配的内存会发生什么变化呢?这会是内存泄漏吗? 在我的示例中,数据对象在函数终止后是否仍然有效,或者它只是偶然工作,在更复杂的实例中容易出现未定义的行为? 在本例中,将delete放在正确的位置? 还是应该避免这种写作方式 int * one (void); int main (void){ int *two = new int; *two = *one (); cout << "

在函数中注册新指针时会发生什么? 我承认,应该销毁指针的名称。 但是分配的内存会发生什么变化呢?这会是内存泄漏吗? 在我的示例中,数据对象在函数终止后是否仍然有效,或者它只是偶然工作,在更复杂的实例中容易出现未定义的行为? 在本例中,将delete放在正确的位置? 还是应该避免这种写作方式

int * one (void);

int main (void){
    int *two = new int;
    *two = *one ();
    cout << "Address: " << one() << "|" << *one() << endl; // Address: 0xe51a78|5555
    cout << "Address: " << two << "|" << *two << endl;  // Address: 0xe519d8|5555
}

int * one (void){
    int * pFun = new int; // declaration of a pointer inside a function
    *pFun = 5555;
    return pFun;
}
int*one(无效);
内部主(空){
int*two=新的int;
*二=*一();

cout您编写的代码将泄漏

==365== Memcheck, a memory error detector
==365== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==365== Using Valgrind-3.17.0.GIT and LibVEX; rerun with -h for copyright info
==365== Command: ./test
==365== 
==365== 
==365== HEAP SUMMARY:
==365==     in use at exit: 8 bytes in 2 blocks
==365==   total heap usage: 3 allocs, 1 frees, 72,712 bytes allocated
==365== 
==365== 4 bytes in 1 blocks are definitely lost in loss record 1 of 2
==365==    at 0x484D103: operator new(unsigned long) (vg_replace_malloc.c:342)
==365==    by 0x10919E: main (in /petsc/test)
==365== 
==365== 4 bytes in 1 blocks are definitely lost in loss record 2 of 2
==365==    at 0x484D103: operator new(unsigned long) (vg_replace_malloc.c:342)
==365==    by 0x1091CC: one() (in /petsc/test)
==365==    by 0x1091A7: main (in /petsc/test)
==365== 
==365== LEAK SUMMARY:
==365==    definitely lost: 8 bytes in 2 blocks
==365==    indirectly lost: 0 bytes in 0 blocks
==365==      possibly lost: 0 bytes in 0 blocks
==365==    still reachable: 0 bytes in 0 blocks
==365==         suppressed: 0 bytes in 0 blocks
==365== 
==365== For lists of detected and suppressed errors, rerun with: -s
==365== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
注意:对于以上内容,我删除了两个打印调用,因为第一个调用多调用了两次
one()
,导致另外两次泄漏

您从不直接存储由
one()
返回的指针,而是立即取消引用它。这会导致抛出该地址。更好的方法是执行以下操作:

// two is an uninitialized pointer
int *two;
// Assign the returned pointer to two
two = one();
// Assign the value pointed to by two (and in effect one()) to three and use it
int three = *two;
functionThatExpectsAnInt(three);
// Alternatively use two directly, it points to valid memory whose value has not changed
functionThatExpectsAnInt(*two);
// Clean up resources from one()
delete two;

对于返回已分配内存的函数,调用者是该函数返回的资源的有效“所有者”。因此调用者必须释放资源,或将资源传递给另一个将要释放的函数。

动态分配的对象存在,直到它被取消分配或“释放”.这正是动态分配的目的:创建对象,其生存期不依赖于作用域(即,不在下一个闭合大括号结束,如自动变量),也不无限,如全局或静态变量。相反,动态分配对象的生存期完全由运行时决定,“动态”

返回指向动态分配对象的指针是一种常见的模式,例如


Jacob说得对,您的程序没有释放分配的对象。在程序结束之前的某个时间释放所有资源(包括打开的文件、套接字和系统资源的其他句柄)是一种好的方式。但这会有什么不同吗?不会,因为(同时链接的答案也说明了清理的必要性:-)。您的程序可以正常运行任意次数,而不会耗尽内存。

此处的讨论可能与此相关