小编use*_*926的帖子

的std :: enable_shared_from_this; 公共与私人

我正在玩一些使用shared_ptr和enable_shared_from_this,而我遇到了一些我不太懂的东西.

在我的第一次尝试中,我构建了这样的东西:

class shared_test : std::enable_shared_from_this<shared_test> {
public:
    void print(bool recursive) {
        if (recursive) {
            shared_from_this()->print(false);
        }

        std::cout << "printing" << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,此类私有地扩展std :: enable_shared_from_this.这显然有很大的不同,因为执行这样的事情:

int main() {
    auto t(std::make_shared<shared_test>());
    t->print(true);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

抛出bad_weak_ptr异常.好像我从std :: enable_shared_from_this中将类定义更改为公开的,这就是find.

为什么,我在这里想念什么?并没有办法使它适用于私有继承,因为shared_test类的"外部世界"不需要知道它是否允许共享...(至少,如果你问我,还是我又想念一些东西?)

c++ shared-ptr private-inheritance c++11 enable-shared-from-this

15
推荐指数
2
解决办法
1719
查看次数

什么时候允许编译器优化复制构造函数

今天,我遇到了一些我对复制构造函数不太了解的内容。

考虑下面的代码:

#include <iostream>
using namespace std;

class some_class {
  public:
    some_class() {

    }

    some_class(const some_class&) {
      cout << "copy!" << endl;
    }

    some_class call() {
      cout << "is called" << endl;
      return *this;  // <-- should call the copy constructor
    }
};

some_class create() {
  return some_class();
}

static some_class origin;
static some_class copy = origin; // <-- should call the copy constructor

int main(void)
{
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后在将原点分配给副本时调用副本构造函数,这很有意义。但是,如果我将复制声明更改为

static some_class copy = some_class();
Run Code Online (Sandbox Code Playgroud)

它没有被调用。即使在使用该create()函数时,它也不会调用复制构造函数。但是,将其更改为

static …
Run Code Online (Sandbox Code Playgroud)

c++ copy-constructor language-lawyer copy-elision

4
推荐指数
1
解决办法
346
查看次数