vendredi 3 septembre 2021

Why it needs a rvalue copy constructor even it won't be called?

I've wrote a shared_ptr the class definition is as below:

template <typename T>
class shared_ptr {
private:
...
public:
  shared_ptr(T* p);
  shared_ptr(shared_ptr& src);
  shared_ptr& operator=(shared_ptr const& src);
};
shared_ptr<T> make_shared(Args&&... args) {
  return shared_ptr<T>(new T(std::forward<Args>(args)...));
}
// the function call:
shared_ptr<int> a = make_shared<int>(1);

it won't work and the compiler error me that

non-const lvalue reference to type shared_ptr<> cannot bind to rvalue of type shared_ptr<>

I add a rvalue copy constructor:

template <typename T>
shared_ptr(shared_ptr&& src) {
  print("rvalue");
}

But no statement are printed out.

my environment is visual studio 2019 with MSVC++.

if my rvalue copy constructor is not executed, why it errors when there is no rvalue copy constructor? (I guess it's a RVO but seems it's not)

thank you all for the answer and comment , I will learn to answer good question next time.

Aucun commentaire:

Enregistrer un commentaire