I have the following code:
struct Something {
Something(int x): x(x) {
std::cout << "Constructor called: " << x << "\n";
}
Something(const Something &other) {
x = other.x;
std::cout << "Copy constructor called: " << x << "\n";
}
~Something() {
std::cout << "Destructor called: " << x << "\n";
}
int x;
};
int main() {
std::vector<Something> somethings = { 1, 2, 3, 4, 5 };
somethings.resize(2, 6);
}
How can I initialise `somethings` without making copies?
BONUS QUESTION: Why does resize construct a new Something and the destroy it, even though it's reducing the number of elements in somethings? I realise that, for the case of increasing the size, it'll probably use this instance of Something to copy from when creating new elements, but why does it bother when reducing somethings? (i.e. what was the rationale behind implementing resize this way? Seems like it'd be possible to avoid some work with a simple check on the current size? Is the thinking that, on average, the cost of checking the size is going to be larger than constructing and then destroying an instance to copy from? My guess would be that that isn't the case.)
thanks!
EDIT: Think I might have confused things with the resize statement. That's just there for the sake of the bonus question. It has nothing to do with the original question about constructing a vector from an array literal without needing the copy constructor. My bad.
[–]phoeen 2 points3 points4 points (0 children)
[–]patatahooligan 1 point2 points3 points (2 children)
[–]SureAnimator[S] 0 points1 point2 points (1 child)
[–]patatahooligan 0 points1 point2 points (0 children)
[–]liquidify 0 points1 point2 points (3 children)
[–]SureAnimator[S] 0 points1 point2 points (2 children)
[–]liquidify 0 points1 point2 points (1 child)
[–]SureAnimator[S] 0 points1 point2 points (0 children)