nav*_*jan 1 c++ memory-management stl smart-pointers c++11
我有一个类,其对象指针将作为键/数据添加到多个 std::map/std::unordered_map/hash(内部实现)中。为了自动删除对象,我使用了 shared_ptr。
我使用shared_ptr only类设计了我的类。
现在我想确保将来没有人这样做:
#include <memory>
#include <string>
class A {
protected:
struct this_is_private;
public:
explicit A(const this_is_private &) {}
A(const this_is_private &, ::std::string, int) {}
template <typename... T>
static ::std::shared_ptr<A> create(T &&...args) {
return ::std::make_shared<A>(this_is_private{0},
::std::forward<T>(args)...);
}
protected:
struct this_is_private {
explicit this_is_private(int) {}
};
A(const A &) = delete;
const A &operator =(const A &) = delete;
};
::std::map<A*, int> m_error;
::std::map<::std::shared_ptr<A>, int> m_ok;
::std::shared_ptr<A> foo()
{
::std::shared_ptr<A> temp = A::create();
A * obj_ptr = temp.get();
m_error.insert(pair<A*, int>(obj_ptr, 10)); //How to make sure no one do this in future
m_ok.insert(pair<::std::shared_ptr<A>, int>(temp,10)); //ok
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1026 次 |
最近记录: |