从C++ 11开始,由于几个原因,开发人员倾向于将智能指针类用于动态生命周期对象.而对于那些新的智能指针类,标准,甚至建议不使用运营商,new而是建议使用make_shared或make_unique避免一些容易出错.
如果我们喜欢使用智能指针类shared_ptr,我们可以构建一个类似的,
shared_ptr<int> p(new int(12));
Run Code Online (Sandbox Code Playgroud)
我们还希望将自定义删除器传递给智能指针类,
shared_ptr<int> p(new int(12), deleter);
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我们喜欢使用make_shared分配,例如.int,而不是使用new和shared_ptr构造函数,就像上面的第一个表达式,我们可以使用
auto ip = make_shared<int>(12);
Run Code Online (Sandbox Code Playgroud)
但是,如果我们也希望将自定义删除器传递给make_shared,那么有没有正确的方法呢?好像编译器,至少gcc,给出错误,
auto ip = make_shared<int>(12, deleter);
Run Code Online (Sandbox Code Playgroud) QML语言有一个全局对象Qt,它提供了许多有用的枚举和函数.可能这个对象最常用的功能是quit().此功能导致发出QQmlEngine::quit()信号,通常QCoreApplication::quit()由应用程序开发人员连接到插槽.
但问题是,这个函数调用QCoreApplication::exit()返回码0.
我的问题是,是否有一种本地方式告诉应用程序退出QML的指定返回码?对于"native",我指的是直接的方式而不是解决方法或hack(例如,调用可调用的函数).
我使用单例模式,该模式返回对unique_ptr解引用的引用。这是代码,
#include <iostream>
#include <memory>
using std::cout; using std::endl;
using std::unique_ptr;
namespace Settings {
class Lazy {
Lazy() { cout << "Lazy::Lazy() " << this << endl; }
public:
~Lazy() { cout << "Lazy::~Lazy() " << this << endl; }
static Lazy &instance()
{
static unique_ptr<Lazy> lazy(new Lazy);
return *lazy;
}
};
Lazy &lazy()
{ return Lazy::instance(); }
}
int main()
{
cout << "main starts!" << endl;
auto state = Settings::lazy();
cout << "auto state = Settings::lazy() " << …Run Code Online (Sandbox Code Playgroud) c++ ×2
c++11 ×2
lazy-loading ×1
make-shared ×1
qml ×1
qt ×1
shared-ptr ×1
singleton ×1
unique-ptr ×1