Hello:
I'm not sure how to word this question properly, so I'll start by
listing the code I am having problems with:
int main()
{
std::vector<int > x;
x.swap(std::vec tor<int>());
return 0;
}
This is also not allowed:
std::vector<int > get()
{
return std::vector<int >();
}
int main()
{
std::vector<int > x;
x.swap(get());
return 0;
}
I was told on another newsgroup that the following code is
nonstandard C++. The reason being that "Standard C++
doesn't allow a reference to non-const to be bound to a
temporary object."
But being able to bind a reference to non-const to a temporary
object is useful for taking advantage of using a swap method.
I find it useful to be able to avoid this restriction because
it allows me to wrap resources that are expensive to create
and destroy into a class and then move it around while
minimising copying and guaranteeing exception safety by
using a swap function, all in a concise piece of code.
For instance if the Resource class wrapped an expensive
resource and the create static method creates the resource
while the open static method opens the resource:
// Resource interface:
Resource Resource::open( char *name);
Resource Resource::creat e(char *name);
// Some code:
Resource resource1;
Resource resource2;
resource1.swap( Resource::open( "XYZ"));
resource2.swap( Resource::creat e("abc"));
I'm therefore interested in the motivation for this restriction and
if there is another way to do the same job just as efficiently.
-John
I'm not sure how to word this question properly, so I'll start by
listing the code I am having problems with:
int main()
{
std::vector<int > x;
x.swap(std::vec tor<int>());
return 0;
}
This is also not allowed:
std::vector<int > get()
{
return std::vector<int >();
}
int main()
{
std::vector<int > x;
x.swap(get());
return 0;
}
I was told on another newsgroup that the following code is
nonstandard C++. The reason being that "Standard C++
doesn't allow a reference to non-const to be bound to a
temporary object."
But being able to bind a reference to non-const to a temporary
object is useful for taking advantage of using a swap method.
I find it useful to be able to avoid this restriction because
it allows me to wrap resources that are expensive to create
and destroy into a class and then move it around while
minimising copying and guaranteeing exception safety by
using a swap function, all in a concise piece of code.
For instance if the Resource class wrapped an expensive
resource and the create static method creates the resource
while the open static method opens the resource:
// Resource interface:
Resource Resource::open( char *name);
Resource Resource::creat e(char *name);
// Some code:
Resource resource1;
Resource resource2;
resource1.swap( Resource::open( "XYZ"));
resource2.swap( Resource::creat e("abc"));
I'm therefore interested in the motivation for this restriction and
if there is another way to do the same job just as efficiently.
-John
Comment