YI HU
YI HU

Reputation: 11

what is the proper c++ way to initialize reference member

my c++ code is:

template <typename T>
struct myNode {
    T& cargo;
    myNode<T>(T& cargo) : cargo(cargo) {  }
...
...
};

It works.But in the case of myNode<int>,I have to build an int variable and a int reference before construct a new myNode object, like this:

int A = 1;
int&B = A;
myNode<int>& a = *new myNode<int>(B); 

I am wondering how to build a myNode object more directly, like this:

myNode<int>& a = *new myNode<int>(1); 

Thank you all in advance!

Upvotes: 0

Views: 91

Answers (2)

Alberto
Alberto

Reputation: 12929

In my opinion there are a lot going on here... first, it's a bad practice this:

T& obj = *new T(...);

Because then you need to remember to delete it somewhere, and making it a reference, does no more than increasing the chance that you will forget to delete it.

There is also another problem: reference lifetime follows the original object lifetime, so if you pass that object a around your program, you need to be careful, because the A object might have been destructed already.

So to solve the first problem (if you don't have to pass that object around the program), you can simply do something like this:

myNode<int> a(A);

Also keep in mind that as others has already pointer out, you don't need the other statement involving B.

However, if you really really really need that "short version", you can use R value reference:

T& cargo
myNode<T>(T&& param) : param(cargo) {  }

Which will "create for you" a reference to that temporary object 1 (be aware that R value references don't accept non-temporary object, so you also need to keep the other one constructor)

Note: this is actually "useful" if you are dealing with complex and heavy objects, not int

Upvotes: 1

Andrea Grillo
Andrea Grillo

Reputation: 125

int A = 1;
myNode<int>& a = *new myNode<int>(A);

The statement int& B = A; is not necessary.

myNode<int>& a = *new myNode<int>(1); doesn't work due to the type of the member cargo of class myNode. It requires to be a reference to a variable, not an integer literal.

Upvotes: 0

Related Questions