简体   繁体   中英

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?

You have to make a pointer type getter.

template<typename T>
class ptr {
...

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

function(foo->get());
  • Avoid using new . Create a maker function like std::make_unique , std::make_shared .
  • Create Copy/Move constructor/assignment operator. Make correct behavior on each operations.
  • Add const accessor

Automatic conversion from ptr<Foo> fo Foo* is possible:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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