C & C++

C & C++

Made by DeepSource

Found redundant use of constructor on return, instead use the braced initializer list CXX-W2033

Anti-pattern
Minor

The use of constructor on return is considered redundant as the type has already been provided by the return type, and writing the constructor again is of no meaningful value to the program.

Instead of using a constructor on return, you should use a braced initializer list which is more succinct and avoids having to change constructor if the return type is changed but the constructible parameters are still valid.

Bad practice

#include <iostream>
#include <vector>

std::vector<int> getVector() {
    return std::vector<int>(1, 2, 3);
}

int main() {
    auto v = getVector();
    for (auto i : v) {
        std::cout << i << " ";
    }
}

Recommended

#include <iostream>
#include <vector>
#include <tuple>

std::vector<int> getVector() {
    return {1, 2, 3};
}

// works without having to change the body
std::tuple<int, int, int> getTuple() {
    return {1, 2, 3};
}

int main() {
    auto v = getVector();
    for (auto i : v) {
        std::cout << i << " ";
    }
}