Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Discussion

Why passing parameters by value and std::move is preferred in constructors (Sink Arguments) [StackOverflow Architecture Guide]

raii_clean_coder
Modern C++ Advocate
MEMBER
Rozpustnik: 190
Data dołączenia: Aug 2020
Posty: 20
Dzięki: 22
1 miesięcy temu · Jun 29, 2026 11:00 AM
#1

Modern pattern for storing constructor arguments:

CPP
class UserProfile {
    std::string m_name;
    std::vector<int> m_scores;
public:
    // Pass by value, then move into member
    UserProfile(std::string name, std::vector<int> scores)
        : m_name(std::move(name)), m_scores(std::move(scores)) {}
};

If caller passes an rvalue (UserProfile("Alice", {10, 20})), the arguments are constructed once and moved twice with zero deep copies! Avoids having to write separate lvalue and rvalue constructor overloads.

modern_cpp_artisan
C++ Template Wizard
MEMBER
Rozpustnik: 124
Data dołączenia: Jun 2019
Posty: 29
Dzięki: 72
1 miesięcy temu · Jun 29, 2026 3:57 PM
#2

Pass-by-value-then-move (the sink parameter idiom) provides the cleanest balance between brevity and move efficiency for constructor parameters.

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Rozpustnik: 47
Data dołączenia: Feb 2018
Posty: 17
Dzięki: 75
1 miesięcy temu · Jun 30, 2026 4:18 AM
#3

Saves having to maintain $2^N$ combinatorial overloads for constructors with multiple parameters.