简体   繁体   English

C ++:如何在堆栈存储器中创建一个对象,该对象指向生成该对象的对象?

[英]C++: how do I create an object in stack memory that points to the object I am generating it from?

I have a class Foo with a constructor Foo(Bar * b). 我有一个带有构造函数Foo(Bar * b)的Foo类。 I want a function inside of the class Bar that returns a Foo that points to that Bar. 我想要在Bar类中返回一个指向该Bar的Foo的函数。 I try: 我尝试:

Foo& Bar::make_foo() {
  Foo f((Bar*)this);
  return f;
}

but then G++ tells me: 但是G ++告诉我:

error: variable ‘Foo f’ has initializer but incomplete type

now I know this would work fine in heap memory: 现在我知道这在堆内存中可以正常工作:

Foo* Bar::make_foo() {
  Foo * f = new Foo((Bar*)this);
  return f;
}

Edit: apparently the problem was due to an incomplete class defintion. 编辑:显然问题是由于不完整的类定义。 However I am still curious if there is an appropriate idiom for returning an object in stack memory. 但是我仍然很好奇是否有适当的习惯来返回堆栈存储器中的对象。

This code is wrong ANYWAY, since it's returning an object on the stack, which means that once you have returned from the function, that space is available for other objects to be stored in - that's not going to end at all well. 无论如何,这段代码是错误的,因为它正在返回堆栈上的一个对象,这意味着一旦您从函数中返回,该空间将可用于存储其他对象-根本不会结束。

Foo& Bar::make_foo() {
  Foo f((Bar*)this);
  return f;
}

As long as Bar is declared as it should be, you should be able to do this fine - aside from the concern with "you are using stack-space that is going to be freed". 只要声明Bar应该是正确的,您就应该可以做到这一点-除了担心“您正在使用将要释放的堆栈空间”。

The following works for me ( http://codepad.org/feWQYjtt ). 以下对我有用http://codepad.org/feWQYjtt )。 Note: I have slightly changed the signature of make-foo , returning reference of local object does not make sense. 注意:我稍微改变了make-foo的签名,返回本地对象的引用没有任何意义。

struct Bar;
struct Foo {
    Foo( Bar * ) {}
};

struct Bar {
    Foo make_foo() {     // Signature changed
        return Foo( this );
    }
};

int main() {
    Bar barObj;
    Foo fooObj = barObj.make_foo();
    (void) fooObj;
}

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

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