Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the statement “vector<int>(v1);” fail

Tags:

c++

vector

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?

like image 631
Tango Xiao Avatar asked Apr 01 '16 15:04

Tango Xiao


2 Answers

vector<int>(v1); is same as vector<int> v1;. i.e. variable redefinition.

like image 108
αλεχολυτ Avatar answered Nov 14 '22 22:11

αλεχολυτ


vector<int>(v1) expression yields a temporary object, and can be put on the right side of operator=, but if we use vector<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

like image 36
πάντα ῥεῖ Avatar answered Nov 14 '22 22:11

πάντα ῥεῖ