【问题标题】:How can I access dynamically created objects which are created out of the scope of the current function?如何访问在当前函数范围之外创建的动态创建的对象?
【发布时间】:2012-06-07 07:35:54
【问题描述】:

我想将一个未初始化的对象指针传递给某个方法。在该方法中,我将使用new 运算符(或malloc)创建对象的一个​​实例,并将其地址分配给传递的指针。这是我的代码的一部分:

void test(testClass* t){
    ...
    t = new testClass();
    ...
}

int _tmain(int argc, _TCHAR* argv[])
{
    testClass* t = NULL;
    test(t);
    cout<<t->getTestValue()<<endl;
    delete t;
}

我的问题出在_tmain 函数中(在调用test 之后),我想调用t 指向的对象的getTestValue 方法。在这里,我的程序崩溃并以访问冲突意外异常终止。

似乎动态创建的对象(使用运算符new 甚至malloc)在函数test 的范围之外是不可用的。有人可以帮忙吗?

【问题讨论】:

    标签: c++ exception object pointers dynamic


    【解决方案1】:

    要更改函数中的指针,必须通过引用传递:

    void test(testClass*& t)
    

    否则,函数内部所做的更改在外部是不可见的。

    您的原始指针没有改变,仍然是NULL,因此会遇到未定义的行为和崩溃。

    每当您按值传递参数时,都会在函数内部进行复制。因此,当您执行t = new testClass(); 时,您实际上是在处理指针的副本

    【讨论】:

    • 我稍微更改了测试功能,现在一切正常! void test(testClass** t){ ... * t = new testClass(); ... } & 在我的主要方法中: int _tmain(int argc, _TCHAR* argv[]) { testClass* t = NULL;测试(&t); ... }
    • @EhsanKhodarahmi 为什么?使用引用更简单、更清晰。您只需要更改签名,其他什么都不需要。请习惯使用引用。
    • 有些人(例如 Google google-styleguide.googlecode.com/svn/trunk/cppguide.xml)使用约定,将要更改的参数应作为指针传递,而引用只应用于不会更改的参数(暗示引用类型的参数应始终为 const)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多