【发布时间】:2014-11-18 16:25:59
【问题描述】:
我想快速实现一些所谓的“所有者指针”,即确保唯一所有权语义的智能指针,同时提供不让对象保持活动状态但可以测试它是否存在的“观察者”指针是。
我尝试做的最直接的方法是继承std::shared_ptr,并禁用它的复制构造,以便没有其他指针可以实际共享该对象。
这是我现在拥有的:
#include <memory>
#include <iostream>
template <class T>
struct owner_ptr : public std::shared_ptr<T> {
// Import constructors
using std::shared_ptr<T>::shared_ptr;
// Disable copy-construction
owner_ptr(owner_ptr<T> const&) = delete;
// Failed attempt at forbidding what comes next
operator std::shared_ptr<T> const&() = delete;
};
struct Foo {
Foo() {
std::cout << "Hello Foo\n";
}
~Foo() {
std::cout << "G'bye Foo\n";
}
void talk() {
std::cout << "I'm talkin'\n";
}
};
owner_ptr<Foo> fooPtr(new Foo);
int main(int, char**) {
// This should not compile, but it does.
std::shared_ptr<Foo> sptr = fooPtr;
// Simple tests
fooPtr->talk();
(*fooPtr).talk();
// Confirmation that two pointers are sharing the object (it prints "2").
std::cout << sptr.use_count() << '\n';
}
我一直在拉头发。如何禁止从我的 owner_ptr 复制构造 std::shared_ptr ?我不喜欢私下继承然后从std::shared_ptr导入所有东西...
【问题讨论】:
-
你真的想在这里使用组合而不是继承。尤其不是公共基地。这就是你所有麻烦的根源。
-
@Deduplicator 我会将所有内容转发给所述成员,这与我在上一句中所说的完全相同。如果没有别的办法,我会作为最后的手段去做,但我不喜欢它。
-
那么,你想创建类似
std::unique_ptr的东西吗? -
@BЈовић
std::unique_ptr不提供观察者指针,这是我需要的主要功能。 -
究竟什么是“观察者指针”?
标签: c++11 copy-constructor smart-pointers base-class