Passing an object with long lifetime

Is there a way to make sure that you can't do this
 
Add(Vector2(100, 100));


but instead only be able to do this
 
Add(pos);



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Vector2 pos(100, 100);

void Add(Vector2& vector)
{
    //code
}

int main()
{
    //Make sure you can't do this
    Add(Vector2(100, 100));
    
    //Only allow this
    Add(pos);
}
With the code as it is, you won't be able to do Add( Vector2(100, 100) );
(can't use an rvalue to initialise a reference to non-const; an lvalue is required)
http://coliru.stacked-crooked.com/a/842ba05aeba8da88
This code works fine in VS 2015.

I think the website you linked uses clang compiler.

So why does MSVC allow this but not clang.
> So why does MSVC allow this but not clang.

It is a non-standard extension.
warning C4239: nonstandard extension used: 'argument': conversion from 'Vector2' to 'Vector2 &'
note: A non-const reference may only be bound to an lvalue

http://rextester.com/ENJKC34481


Either force standard conformance with -Za
error C2664: 'void Add(Vector2 &)': cannot convert argument 1 from 'Vector2' to 'Vector2 &'
note: A non-const reference may only be bound to an lvalue

http://rextester.com/FPYK48396


Or add this declaration: void Add( Vector2&& ) = delete ;
error C2280: 'void Add(Vector2 &&)': attempting to reference a deleted function
note: see declaration of 'Add'

http://rextester.com/QBM53464
Ok, that is great. It works fine, but can you explain what this line of code does exactly?

 
void Add(Vector2&&) = delete;
Last edited on
It provides an explicitly deleted overload for rvalues.
If the function is invoked with an rvalue argument, overload resolution would select the deleted function and we get a compile-time error.

Deleted functions
If, instead of a function body, the special syntax = delete ; is used, the function is defined as deleted. Any use of a deleted function is ill-formed (the program will not compile). ...

If the function is overloaded, overload resolution takes place first, and the program is only ill-formed if the deleted function was selected.
http://en.cppreference.com/w/cpp/language/function#Deleted_functions


You may want to read this if you are unfamiliar with rvalue references:
http://thbecker.net/articles/rvalue_references/section_01.html
Thank you so much. That was great !

Appreciate the help.
Topic archived. No new replies allowed.