本文介绍了C ++不同类型的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我发现同一指针指令在某种情况下会使应用程序崩溃,而在其他情况下则不会.

in the following code I found that same pointer instruction crash the application in a situation while not in other situation.

#include <iostream>
using namespace std;

int main()
{
    int *p;
    *p = 50;                    //this instruction causes the crash
    int* q = new int;
    *q = 50;                    //this instruction executes ok
    cout << "p:" << p << endl;
    cout << "q:" << q << endl;
    return 0;
}

我想知道为什么会这样吗?

I want to know why this is the case?

推荐答案

我看到您需要一些文档链接:

I see you need some links to documentation:

  • http://en.cppreference.com/w/cpp/language/pointer
  • http://en.cppreference.com/w/cpp/language/operator_member_access
  • http://en.cppreference.com/w/cpp/language/new
  • http://en.cppreference.com/w/cpp/language/delete
  • http://en.cppreference.com/w/cpp/language/storage_duration

总结一下:

  • 您可以使用间接操作符(*)返回指针指向的对象(取消引用指针).
  • 只有当指针实际指向一个对象(默认情况下不会指向该对象)时,您才可以通过指针访问(读取或修改)该对象.
  • 您可以将对象的地址分配给指针,以使指针指向它.
  • 您可以使用地址运算符(&)来获取对象的地址,以将其分配给指针.
  • 您可以使用new运算符创建一个新对象,并将其返回的地址分配给指针.
  • 您必须使用delete最终销毁使用new创建的对象.
  • 使用指针时,您独自负责指针所指向的对象的有效性.当对象在其生命周期结束后泄漏或访问对象时,不要期望编译器会警告您.如果做错了,您可能会观察到未定义的行为.
  • 智能指针可以帮助跟踪对象所有权并进行适当的销毁.
  • You can use the indirection operator (*) to return the object the pointer points to (dereference the pointer).
  • You can only access (read or modify) an object via a pointer, when the pointer actually points to an object (which by default they don't).
  • You can assign the address of an object to the pointer to let the pointer point at it.
  • You can use the address-of operator (&) to acquire the address of an object for assigning it to a pointer.
  • You can use the new operator to create a new object and return the address to it for assigning it to a pointer.
  • You must use delete to eventually destroy objects created using new.
  • When you use pointers, you alone are responsible for the validity of the objects your pointers point to. Don't expect the compiler to warn you when objects are leaked or accessed beyond the end of their lifetime. If you do it wrong, you might observe undefined behavior.
  • Smart pointers can help to keep track of object ownership and take care of proper destruction.

进一步阅读:

  • Can a local variable's memory be accessed outside its scope?
  • What does "dereferencing" a pointer mean?
  • Undefined, unspecified and implementation-defined behavior
  • What is a smart pointer and when should I use one?
  • https://ericlavesson.blogspot.de/2013/03/c-ownership-semantics.html
  • https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e6-use-raii-to-prevent-leaks

这篇关于C ++不同类型的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 01:44