A vector<int>(v1)
expression yields a temporary object, and can be put on the right side of operator=
, but if we use a vector<int>(v1)
expression as a statement, it will fail in Visual Studio 2010 10.0.30319.1 RTMRel. Detailed error information is in comments in the following code. Why does this happen?
vector<int> v1;
v1.push_back( 10 );
v1.push_back( 20 );
v1.push_back( 30 );
vector<int> v3 = vector<int>(v1); //OK, deliberately code like this.
vector<int>(v1); //error C2086: “std::vector<_Ty> v1”: redefinition
In the book “C++ Coding Standards: 101 Rules, Guidelines, and Best Practices”, chapter 82 "Use the accepted idioms to really shrink capacity and really erase elements". There is a statement:
container<_Type>(c).swap(c);
I don’t understand and just want to test container<_Type>(c)
, what does it mean?
vector<int>(v1);
is same as vector<int> v1;
. i.e. variable redefinition.
vector<int>(v1)
expression yields a temporary object, and can be put on the right side ofoperator=
, but if we usevector<int>(v1)
expression as a statement, We will fail ...
The plain statement is handled differently by the compiler:
vector<int>(v1); //error C2086: “std::vector<_Ty> v1”: redefinition
Is an alternative way of writing
vector<int> v1;
So you're redefining v1
and the compiler complains.
To see your temporary initialization working use for instance
void foo(const std::vector<int>& v)
{
}
and call
foo(vector<int>(v1));
or simply1
(std::vector<int>)(v1); // this creates a temporary which is immediately disposed
See live demo for the latter
1)Stolen from @Sergey A's answer, but he preferred to delete it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With