相关疑难解决方法(0)

在基础构造函数完成之前传递`this`:UB还是危险的?

考虑这个最小的例子(我能想到):

struct Bar;

struct Foo {
  Bar* const b;
  Foo(Bar* b) : b(b) {}
};

struct Bar {
  Foo* const f;
  Bar(Foo* f) : f(f) {}
};

struct Baz : Bar {
  Baz() : Bar(new Foo(this)) {}
};
Run Code Online (Sandbox Code Playgroud)

当传递this给ctor时Foo,没有Baz创建层次结构中的任何内容,但是它们既Foo没有Bar收到也没有任何问题.

现在的问题是,this以这种方式放弃或者未定义的行为是否危险?

问题2:如果Foo::Foo(Bar*)Foo::Foo(Bar&)用相同的语义?我必须通过*this,但deref运算符在这种情况下不会做任何事情.

c++ constructor this undefined-behavior

10
推荐指数
3
解决办法
296
查看次数

C++中的循环引用,没有指针

有没有办法在不使用指针的情况下定义循环引用?

我需要有这样的事情:

struct A;
struct B {
    A a;
};

struct A {
    B b;
};
Run Code Online (Sandbox Code Playgroud)

谢谢!

c++ pointers circular-reference

5
推荐指数
3
解决办法
6392
查看次数