我有这个代码不起作用,但我认为意图很明确:
testmakeshared.cpp
#include <memory>
class A {
public:
static ::std::shared_ptr<A> create() {
return ::std::make_shared<A>();
}
protected:
A() {}
A(const A &) = delete;
const A &operator =(const A &) = delete;
};
::std::shared_ptr<A> foo()
{
return A::create();
}
Run Code Online (Sandbox Code Playgroud)
但是我在编译时遇到了这个错误:
g++ -std=c++0x -march=native -mtune=native -O3 -Wall testmakeshared.cpp
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:52:0,
from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/memory:86,
from testmakeshared.cpp:1:
testmakeshared.cpp: In constructor ‘std::_Sp_counted_ptr_inplace<_Tp, _Alloc, _Lp>::_Sp_counted_ptr_inplace(_Alloc) [with _Tp = A, _Alloc = std::allocator<A>, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’:
/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr_base.h:518:8: instantiated from ‘std::__shared_count<_Lp>::__shared_count(std::_Sp_make_shared_tag, _Tp*, const _Alloc&, _Args&& …Run Code Online (Sandbox Code Playgroud) 我试图推断出类的构造函数参数的类型.我已成功获取成员方法的参数类型,但我的方法因构造函数而失败,因为它依赖于获取指向成员方法的指针类型.
#include <tuple>
#include <type_traits>
// Some type with a constructor
struct foo {
foo(int, double) {}
void test(char, char) {};
};
// Extract the first parameter
template<class T>
struct func_traits {};
template<class Return, class Type, class ... Params>
struct func_traits<Return(Type::*)(Params...)> {
using params = std::tuple<Params...>;
};
// Get the parameters for foo::test
using test_type = decltype(&foo::test);
using test_params = typename func_traits<test_type>::params;
static_assert(std::is_same<test_params, std::tuple<char, char>>::value, "Not the right tuple");
// Get the parameters for foo::foo
using ctor_type = decltype(&foo::foo); // …Run Code Online (Sandbox Code Playgroud) 我想创建一个类的共享指针,并有一个工厂方法返回它,同时保持构造函数\析构函数的保护.由于共享指针无法访问构造函数或析构函数,因此出现编译错误.
我正在使用llvm 4.1,但我正在寻找一个可以独立于编译器的解决方案(除了使构造函数\析构函数公开).
这是一个代码示例:
class Foo
{
public:
static std::shared_ptr<Foo> getSharedPointer()
{
return std::make_shared<Foo>();
}
protected:
Foo(int x){}
~Foo(){}
};
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
我有一个带有私有构造函数的单例类。在静态工厂方法中,我执行以下操作:
shared_ptr<MyClass> MyClass::GetInstance()
{
static once_flag onceFlag;
call_once(onceFlag, []() {
if (_instance == nullptr)
_instance.reset(new MyClass());
});
return _instance;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用
_instance = make_shared<MyClass>();
Run Code Online (Sandbox Code Playgroud)
该代码无法编译。我的问题是:为什么new可以调用私有构造函数却make_shared不能?