Template function parameter, passing by reference, instead of copy/pointer

Due to the nature of this requirement, I've made a very minimal example, which would adequately solve my issue, without resorting to use of pointers or copy constructors.

Basically I'm trying to pass an object as a reference to the template function, rather than a copy as it's seeing. I'm needing to do this without editing Obj::Call to accommodate a reference as its first parameter, as it'd break other calls.

You'll notice in the following code the object will be destroyed upon passing, while the object defined is still in-scope due to the infinite end loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
using namespace std;

class Obj
{
public:
   string name;

   Obj(string name): name(name) {cout << "create " << this << endl;}
   ~Obj() {cout << "destroy" << endl;}

   template <class T>
      static void Call(T value)
   {
      cout << "Value: " << &value << endl;
   }
};

int main()
{
   Obj obj("Hello");
   Obj::Call(obj);
   while(1);
}


In the past I tried ref(), which appeared to stop this happening, however it created a blank copy of the object instead.
Last edited on
1
2
template <class T>
static void Call(T& value)

Otherwise it will be value semantics.

Edit: did not read what do you need first time. What problems do you have with ref()?
Works fine for me: object is passed. But note that althought it would behave like reference, it would not have same address as original

You'll notice in the following code the object will be destroyed upon passing
You do understand that it is copy which got destroyed and not original object, do you?

EDIT 2:
Did you thy to explicitely provide template parameters?
Obj::Call<Obl&>(obj);
Last edited on
Unfortunately when the copy was destroyed, the data it encapsulates also gets destroyed, I have omitted that from this example.

Strangely when ref was used, it created an empty object and passed that as a reference. So the data contained was garbage.

I've resorted to the specified template parameters, it's just one of those irritating loose ends for me.
Last edited on
Unfortunately when the copy was destroyed, the data it encapsulates also gets destroyed
Strangely when ref was used, it created an empty object and passed that as a reference
Looks like there is something wrong with your class. First quote tells me that you do not have proper copy constructor for class.
Topic archived. No new replies allowed.