J
John Ky
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::vector<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:pen(char *name);
Resource Resource::create(char *name);
// Some code:
Resource resource1;
Resource resource2;
resource1.swap(Resource:pen("XYZ"));
resource2.swap(Resource::create("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::vector<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:pen(char *name);
Resource Resource::create(char *name);
// Some code:
Resource resource1;
Resource resource2;
resource1.swap(Resource:pen("XYZ"));
resource2.swap(Resource::create("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