Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by reference of objects created 'on the fly'

Tags:

c++

reference

My apologies if this question has been answered already - I have searched, but it's a difficult search term to find due to the sheer number of more general questions on passing by reference.

The problem I have is that I am getting a level 4 warning when I compile this sort of thing:

class MyClass
{
public:
    MyClass() {};
};

void DoSomethingToMyClass(MyClass& my_class_reference);


void MyRoutine()
{
    DoSomethingToMyClass(MyClass());
};

The warning (C4239) basically says that there is a dodgy cast from an instance to a reference. I have learnt from careful inspection not to write-off level 4 warnings, as many of them have identified bugs in my (and others') code, such as returning -1 as a size_t (bonus points for knowing what size_t(-1) actually is).

Can anybody explain to me what the code above will actually do? My most paranoid theory is that:

  • An instance of MyClass() is created on-the-fly, but not given a proper handle.
  • Operations performed on my_class_reference reference are then mis-firing.

The other extreme is that C4239 can always be ignored...

*[An analogous situation is when somebody defaults a reference:

void DoSomethingToMyClass(MyClass& my_class_reference=MyClass());

This generates the same warning, but is partially covered in another topic.]*

EDIT:

Thanks for the quick response, guys. Sorry: should have mentioned it's VC++ in Visual Studio.

like image 690
Mike Sadler Avatar asked Jan 27 '26 04:01

Mike Sadler


1 Answers

You get the warning because that's not standard C++, but a MS extension that allows you to bind temporaries to non-const references.

Just don't. Either have the parameter a const reference:

void DoSomethingToMyClass(const MyClass& my_class_reference);

which might not apply here, as the name implies the method mutates the class, or create the object beforehand:

MyClass x;
DoSomethingToMyClass(x);
like image 120
Luchian Grigore Avatar answered Jan 29 '26 16:01

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!