简体   繁体   English

对于我的智能指针,我能做些什么而不是更好?

[英]What can I do instead of this that's better, for my smart pointers?

What the question asks.问题问什么。 I know this works, but is it good practice or bad practice?我知道这行得通,但这是好的做法还是坏的做法? Another example that I've seen someone use, and I've been using it myself, but it doesn't feel right.另一个我看到有人用的例子,我自己也一直在用,但感觉不对。

// in some header file

template <class T>
class ptr {
private:
    T* pointer;
public:
    explicit ptr (T* p = NULL) : pointer(p) { }
    ~ptr()                                  { delete (pointer); }
    T& operator *()                         { return *pointer; }
    T* operator ->()                        { return pointer; }
};
// in some source file, probably main.cpp
ptr<Foo> foo(new Foo());

function(foo->self()); // using function(foo) doesn't work because it can't
                       // convert ptr<Foo> to Foo*
// somewhere inside definition of Foo
Foo* self() { return this; }

Why wouldn't it work unless I included the self() function, and how can I pass the object into the function without it?除非我包含self() function,否则为什么它不起作用,如果没有它,我如何将 object 传递给 function?

You have to make a pointer type getter.你必须制作一个指针类型的getter。

template<typename T>
class ptr {
...

  const T* get() const { return pointer; }
  T* get() { return pointer; }
}

function(foo->get());
  • Avoid using new .避免使用new . Create a maker function like std::make_unique , std::make_shared .创建一个制造商 function 像std::make_uniquestd::make_shared
  • Create Copy/Move constructor/assignment operator.创建复制/移动构造函数/赋值运算符。 Make correct behavior on each operations.对每个操作做出正确的行为。
  • Add const accessor添加 const 访问器

Automatic conversion from ptr<Foo> fo Foo* is possible:可以从ptr<Foo> fo Foo*自动转换:

template <class T>
class ptr {
    private:
        T* pointer;
    public:
        operator T*() { return pointer; }
    // rest of code

but having it would defeat the idea of smart pointers, so smart pointer classes from the standard library do not include it.但是拥有它会破坏智能指针的想法,因此标准库中的智能指针类不包含它。 Instead, they have something like相反,他们有类似的东西

    T* get() { return pointer; }

so that such conversions are explicit.所以这样的转换是明确的。

Most of the time you should just use one of the standard library classes.大多数时候,您应该只使用标准库类之一。 If you need to create your own smart pointer, it is recommended to avoid the inclusion of operator T*() (and avoid automatic conversions in general).如果您需要创建自己的智能指针,建议避免包含operator T*() (并且通常避免自动转换)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM